I am writing a game on js (platformer). The player is presented in the form of a square, tile cards - also squares. On each frame, I determine if there is a player’s collision with any of the nearest tiles:

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!'); } 

Thus, I determine if there is a collision at all, but how to determine if a collision occurred, which side exactly did the player encounter with the tile? Considering that this is a trivial task when developing games, there must be some kind of classical algorithm for solving it. What is he like?

  • Can I find out why you need to know which side you ran into? And looking ahead, I’ll say that in 2D platformers, they usually determine the direction in which the player is facingRight = true; by default, facingRight = true; and then when you turn the player, change this variable - Alexey Shimansky
  • I need to know this for several purposes. For example, to understand whether a player jumped on a platform or not. If he touched it with the right side, then no, if the lower side means yes. The second example is the enemies. If a player touches the enemy with a downside, the enemy dies; if any other player dies (as in Mario). For information about the default direction of the player thanks. - aim777

1 answer 1

Calculate the coordinates of the center 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 in d you will have the direction from one square to another. For example, if dx is greater than zero, then one square is to the right of the other. Or you can calculate the angle by tangent.

  • But what about the fact that a square can touch another square with only one side and two values ​​are obtained (dx and dy)? After all, a square cannot collide with another square, both the bottom and the right side at the same time. - aim777
  • A square may collide diagonally. For example, the square shifted to (1,1) and became in contact with the other in one pixel at the vertex. This is neither top nor left, but diagonally. Depending on your physics, you can get into a lot or a little. If this can not be, then take the maximum value of the module and see if it is more or less than zero. So there will be 4 options. - VIP
  • Can be a little more about this method? What do you mean when you say that you can touch a lot or a little? Penetration depth? - aim777
  • imgur.com/zx1HpAP - here from which side which squares intersect? Above? Below? - VIP
  • Blue underside, red either bottom or right, green either top or left - aim777