I’m working on a game and having trouble with horizontal collision detection between the player and block objects. The collision seems to work fine when the player collides from below the block, but not when moving horizontally.
update() {
// Apply gravity
this.velocity.y += this.gravity;
this.position.y += this.velocity.y;
this.position.x += this.velocity.x;
// Update hitbox position
this.hitbox.position.x = this.position.x + 50;
this.hitbox.position.y = this.position.y + 10;
// Check for collisions
this.checkForHorizontalCollisions();
this.checkForVerticalCollisions();
// Draw the player and hitbox for debugging
ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
ctx.fillRect(this.hitbox.position.x, this.hitbox.position.y, this.hitbox.width, this.hitbox.height);
this.draw();
// Reset velocity.x for movement logic
this.velocity.x = 0;
if (keys.a.pressed) {
this.switchSprite("runLeft");
this.velocity.x = -5;
} else if (keys.d.pressed) {
this.switchSprite("runRight");
this.velocity.x = 5;
} else {
this.switchSprite(this.lastDirection === "left" ? "idleLeft" : "idleRight");
}
}
checkForHorizontalCollisions() {
for (let i = 0; i < this.collisionBlocks.length; i++) {
const collisionBlock = this.collisionBlocks[i];
// if a collision exists
if (
this.position.x <= collisionBlock.position.x + collisionBlock.width &&
this.position.x + this.width >= collisionBlock.position.x &&
this.position.y + this.height >= collisionBlock.position.y &&
this.position.y <= collisionBlock.position.y + collisionBlock.height
) {
// collision on x axis going to the left
if (this.velocity.x < 0) {
const offset = this.position.x - this.position.x;
this.position.x = collisionBlock.position.x + collisionBlock.width - offset + 0.01;
break;
}
if (this.velocity.x > 0) {
const offset = this.position.x - this.position.x + this.width;
this.position.x = collisionBlock.position.x - offset - 0.01;
break;
}
}
}
}
checkForVerticalCollisions() {
for (let i = 0; i < this.collisionBlocks.length; i++) {
const collisionBlock = this.collisionBlocks[i];
// if a collision exists
if (
this.position.x <= collisionBlock.position.x + collisionBlock.width &&
this.position.x + this.width >= collisionBlock.position.x &&
this.position.y + this.height >= collisionBlock.position.y &&
this.position.y <= collisionBlock.position.y + collisionBlock.height
) {
if (this.velocity.y < 0) {
this.velocity.y = 0;
const offset = this.position.y - this.position.y;
this.position.y = collisionBlock.position.y + collisionBlock.height - offset + 0.01;
break;
}
if (this.velocity.y > 0) {
this.velocity.y = 0;
const offset = this.position.y - this.position.y + this.height;
this.position.y = collisionBlock.position.y - offset - 0.01;
break;
}
}
}
}
I’ve also tried creating a hitbox for the player object, but it doesn’t seem to resolve the issue. The problem seems to occur specifically when moving horizontally. Any help would be greatly appreciated!