//*** DETECTING & RESOLVING COLLISION ***//
handleCollisions() {
var player = this.player;
// As long as they are colliding (Be careful for infinite loops)
while (this.hasCollision()) {
// get current x direction
const xDir = this.getXDirection();
// get current y directdiondirection
const yDir = this.getYDirection();
// move the player 1 unit back the direction it came from
player.x -= xDir;
player.y -= yDir;
}
...
}
// returns true if the player is colliding with the box
hasCollision() {
const player = this.player;
const box = this.box;
return (
player.x + player.width / 2 > box.x - box.width / 2 &&
player.x - player.width / 2 < box.x + box.width / 2 &&
player.y + player.height / 2 > box.y - box.height / 2 &&
player.y - player.height / 2 < box.y + box.height / 2
);
}
// returns 1, -1, or 0 if not moving
getXDirection() {
if (this.controls.isDown("right")) {
return 1;
} else if (this.controls.isDown("left")) {
return -1;
} else {
return 0;
}
}
// returns 1, -1, or 0 if not moving
getYDirection() {
if (this.controls.isDown("up")) {
return -1;
} else if (this.controls.isDown("down")) {
return 1;
} else {
return 0;
}
}
In response to a comment about not being able to slide along an edge here is a link to an enhanced version of this same method that allows sliding along edges when colliding. I'm just adding thisAll that changed was to showseparate the X and Y checks into separate loops. I hope this helps demonstrate how simply enhancements can be added toeasily this basic method can be enhanced to meet specific needs.