I have written an algorithm which resolves collisions between axis aligned rectangles so that they are resting against one another after collision resolution.
The code is in Java using LibGDX
public class Rectangle
{
public Vector2 position;
public float halfW, halfH;
private Vector2 restingDistance, currentDistance, overlap;
public Rectangle(Vector2 position, float halfW, float halfH)
{
this.position = position;
this.halfW = halfW;
this.halfH = halfH;
this.restingDistance = new Vector2();
this.currentDistance = new Vector2();
this.overlap = new Vector2();
}
public boolean intersects(Rectangle rectangle)
{
return (position.x - halfW < rectangle.position.x + rectangle.halfW &&
position.x + halfW > rectangle.position.x - rectangle.halfW &&
position.y - halfH < rectangle.position.y + rectangle.halfH &&
position.y + halfH > rectangle.position.y - rectangle.halfH);
}
public void resolveCollision(Rectangle rectangle)
{
// Calculate the resting distance of the two rectangles
restingDistance.set(halfW + rectangle.halfW, halfH + rectangle.halfH);
// Calculate the current distance between the two rectangles
currentDistance.set(position.x - rectangle.position.x, position.y - rectangle.position.y);
// Calculate the overlap between the two rectangles
overlap.set(restingDistance.x - Math.abs(currentDistance.x), restingDistance.y - Math.abs(currentDistance.y));
// Remove the overlap of the axis with the greater overlap
overlap.set(overlap.x < overlap.y ? overlap.x : 0, overlap.y < overlap.x ? overlap.y : 0);
// Reverse the direction of the overlap depending on the positions of the rectangles
overlap.set(position.x < rectangle.position.x ? -overlap.x : overlap.x, position.y < rectangle.position.y ? -overlap.y : overlap.y);
// Add the overlap to the rectangles position
position.add(overlap);
}
}
The code is used like this
if(rectangle1.intersects(rectangle2))
{
rectangle1.resolveCollision(rectangle2);
}
From my testing the code works. Colliding rectangles are moved out of collision so that they are resting against one another. Are there any problems with the way the code resolves collisions? Can the collision resolution code be improved and if so how? Thank you.