I am trying to understand and implement AABB collision to learn simple 2D game physics. I'm following a tutorial and its method is a bit different to other websites. It uses the center of the object and its "half-size" to determine collision. This is its code:
public bool Overlaps(AABB other)
{
if ( Mathf.Abs(center.x - other.center.x) > halfSize.x + other.halfSize.x ) return false;
if ( Mathf.Abs(center.y - other.center.y) > halfSize.y + other.halfSize.y ) return false;
return true;
}
And this is the seemingly more popular option:
if (rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y) {
// collision detected!
}
Which one is more efficient? And for the first option, would I define the center and half-size like this:
AABB = new AABB(new Vector2(Width / 2, Height / 2), new Vector2(Width / 2, Height / 2));
Center and half-size method source: https://gamedevelopment.tutsplus.com/tutorials/basic-2d-platformer-physics-part-1--cms-25799
Position and width/height source: https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection