Files
penguin-jump-p5js/character.js
Daniel Legt 5ccf54d00c feat(character): restrict jumping to when on a platform
Change the jump() condition from checking velocity to detecting whether the character's feet are touching a platform. This prevents mid-air jumps and makes jump behavior more intuitive for platformer gameplay.
2026-06-24 20:00:25 +03:00

87 lines
2.5 KiB
JavaScript

var c = {
velocity: {
x: 0,
y: 0,
},
pos: {
x: 0,
y: 0,
},
size: 50,
img: null,
jump() {
const feet = this.pos.y + this.size;
const onPlatform = getPlatforms().some(p => {
const overlapsX =
this.pos.x + this.size > p.position.x &&
this.pos.x < p.position.x + p.size.x;
const touchesTop =
Math.abs(feet - p.position.y) < 2;
return overlapsX && touchesTop;
});
if (onPlatform) {
this.velocity.y = -5;
}
},
step() {
// Apply Gravity on our velocity.
this.velocity.y = this.velocity.y + 0.15;
// Check for collision with platform ONLY WHEN FALLING.
if ( this.velocity.y > 0 ) {
let newY = false;
let charXLeft = this.pos.x;
let charXRight = this.pos.x + this.size;
let charYTop = this.pos.y
let charYBottom = this.pos.y + this.size
for ( let p of getPlatforms() ) {
// Is the X coord colliding?
let isXColliding = false;
let pLeft = p.position.x;
let pRight = p.position.x + p.size.x;
let pTop = p.position.y;
let pBot = p.position.y + p.size.y;
// Check Left/Right collision
if ( charXLeft < pRight && charXLeft > pLeft ) {
isXColliding = true;
} else if ( charXRight < pRight && charXRight > pLeft ) {
isXColliding = true;
}
if ( isXColliding ) {
// Check if touching platform
if ( charYBottom < pBot && charYBottom > pTop ) {
newY = pTop - this.size;
break;
}
}
}
if ( newY != false ) {
this.velocity.y = 0;
this.pos.y = newY;
}
}
// Applying the velocity to our character position
this.pos.x = this.pos.x + this.velocity.x;
this.pos.y = this.pos.y + this.velocity.y;
this.pos.x = mouseX;
},
draw() {
fill(255, 125, 125);
if ( this.img != null ) {
image(this.img, c.pos.x, c.pos.y, this.size*1.25, this.size*1.25);
}
// square(c.pos.x, c.pos.y, c.size)
}
}