I've just started getting into 2D game development and have been experimenting with some 2D collision and correction logic in canvas. I'm trying to debug this block of code and understand why it is not triggering any intersections vertically except when you flip the comparison sign for the previous states comparison to find which direction it comes in at but with them flipped it reads weird and makes no sense to me.
// this sets up a scenario where the player is intersecting the obstacle and
// its previousY tells us it should be colliding from the top of the obstacle with the bottom of the player
const player = {
x: 100,
y: 322,
width: boxSize,
height: boxSize,
previousX: 100,
previousY: 300
}
const obstacle = createObstacle(
100,
300,
30,
70
)
function checkCollision(player, obstacle) {
const playerTop = player.y
const playerBottom = player.y + player.height
const obstacleTop = obstacle.y
const obstacleBottom = obstacle.y + obstacle.height
// broad collision (this is triggered no problem)
if (
player.x + player.width > obstacle.x
&& player.x < obstacle.x + obstacle.width
&& player.y + player.height > obstacle.y
&& player.y < obstacle.y + obstacle.height
) {
console.log(`Player Bottom: ${playerBottom}, Player Top: ${playerTop}`);
console.log(`Previous Bottom: ${player.previousY + player.height}, Previous Top: ${player.previousY}`);
console.log(`Obstacle Top: ${obstacleTop}, Obstacle Bottom: ${obstacleBottom}`);
if (
playerBottom >= obstacleTop &&
player.previousY + player.height < obstacleTop
) {
console.log('hitting top of obstacle')
} else if (
playerTop <= obstacleBottom &&
player.previousY > obstacleBottom
) {
console.log('hitting bottom of obstacle')
}
}
}
checkCollision(player, obstacle)
```