Games conflict. How to determine the side one square ran into the other?
-
I'm writing a js game. The game is presented as a square, the map's timeline is also square. On every foot, I'll determine if there's a player's clash with any of the closest secrets:
if (a.position.x <= b.position.x + b.width && a.position.x + a.width >= b.position.x && a.position.y <= b.position.y + b.height && a.height + a.position.y >= b.position.y) { console.log('Collision!'); }
So I'm gonna determine if there's a collision in general, but how do you figure out if the collision happened, which side of the player has encountered a mystery? Given that this is a trivial task in the design of games, there's probably some classic algorithm to deal with it. What's he like?
-
Identify the coordinates of the centre of each square, then the difference
var acenter = { x: a.position.x + a.width / 2, y: a.position.y + a.height / 2 }; var bcenter = { x: b.position.x + b.width / 2, y: b.position.y + b.height / 2 }; var d = { x: acenter.x - bcenter.x, y: acenter.y - bcenter.y };
Then you'll have one square to another. For example, if d.x is more than zero, one square to the right of another. Or tangenes can count the angle.