With the following code, collisions are detected, but sides are incorrectly registered.
public int checkBoxes(int aX, int aY, int aWidth, int aHeight, int bX, int bY, int bWidth, int bHeight){
/*
* Returns int
* 0 - No collisions
* 1 - Top
* 2 - Left
* 3 - Bottom
* 4 - Right
*/
Vector2f aMin = new Vector2f(aX, aY);
Vector2f aMax = new Vector2f(aX + aWidth, aY + aHeight);
Vector2f bMin = new Vector2f(bX, bY);
Vector2f bMax = new Vector2f(bX + bWidth, bY + bHeight);
float left = bMin.x - aMax.x;
float right = bMax.x - aMin.x;
float top = bMin.y - aMax.y;
float bottom = bMax.y - aMin.y;
if(left > 0) return 0;
if(right < 0) return 0;
if(top > 0) return 0;
if(bottom < 0) return 0;
int returnCode = 0;
if (Math.abs(left) < right)
{
returnCode = 2;
} else {
returnCode = 4;
}
if (Math.abs(top) < bottom)
{
returnCode = 1;
} else {
returnCode = 3;
}
return returnCode;
}
When A is colliding with the top, left, or right of shape B, the number 3 is returned, and when colliding with the bottom, the number 1 is returned. I don’t really know what’s causing this. What is wrong with my code?
The problem is you are checking for one side, but when you check for left by example and the bottom is also collided you are neglecting that one. I tested the code here: http://wonderfl.net/c/i90L
What I did was first getting the distances for the X and Y of the sides. And then checking which distance was the biggest, multiplied by the size of the rectangle itself, because that side will always be the good edge on a square.