Home javascript collisions in games. How to determine the side, which one square encountered...

# collisions in games. How to determine the side, which one square encountered another?

Author

Date

Category

I write a game on JS (platformer). The player is represented in the form of a square, the tiles of the cards are also squares. At each frame I define whether there is a player’s collision fact with any of the nearest tiles:

``````if (a.position.x & lt; = b.position.x + b.width & amp; & amp;
a.position.x + a.width & gt; = b.position.x & amp; & amp;
a.position.y & lt; = b.position.y + B.Height & amp; & amp;
A.Height + a.position.y & gt; = b.position.y) {
Console.log ('Collision!');
}
``````

So I define whether there is a collision in general, but how to determine if the collision happened, which is the side of the player encountered a tile? Considering that this is a trivial task in developing games, probably there is some kind of classic algorithm for solving it. What is he?

Calculate the coordinates of the center of each square, then the difference

``````var acter = {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 a direction from one square to another. For example, if D.x is greater than zero, then one square is right than the other. Or on tangent an angle can be calculated.

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.