If you want to do a “AABB vs AABB” test here´s a vector based way to do it.
You need some vectors for the boxes: center, half the width and half the height.
You also need a vector to store the result: minimum translation vector.
minimumTranslationVector.x = Math.abs(this.center.x - other.center.x) - (this.halfWidth + other.halfWidth);
minimumTranslationVector.y = Math.abs(this.center.y - other.center.y) - (this.halfHeight + other.halfHeight);
if(minimumTranslationVector.x < 0 && minimumTranslationVector.y < 0)
//Collision
What this mean is that you test one axis at a time for overlap. The absolut value ( = positive value) of “(this.center - other.center)” puts the center position close to zero and then you add half the size of the box. If the “subtracted position” is greater than the size of the boxes, you get a positive value and there is no overlap. If the “subtracted position” is smaller than the size of the boxes, you get a negative value.
That is all if we just want to test intersection, but what is the “minimum translation vector” (I´m just gonna call it by it´s abbreviation “mtv” from now on)? This is a little bonus: it is the smallest amount you have to push back an object for it to NOT be intersecting. This is often a problem in collision detection, that you get stuck too deep in a collision so you can´t get out. So how do you use the mtv? One way is to see what axis is has the smallest intersection and push it back that way. Let´s say you´re testing collision between a Player and a Wall:
- Get the vector from the center of the player to the center of the wall: Wall.center - Player.center.
- Find out on which axis has the smallest intersection (let´s just say in this case it is x)
- player.position.x += mtv.x.
The result is that the player is positioned precisely outside the collision every collision check.
I hope it helps.
(any errors I blame on the very, very late hour over here… :))