# Fast & simple AABB collision detection

It seems that not too many people know this technique, though it is very simple.

It should take up roughly the same amount of time as 2 circle checks.

Here is AABB.class

``````
public class AABB
{
protected Vector2Float pos, size;

public AABB(Vector2Float pos, Vector2Float size)
{
this.pos = pos;
this.size = size;
}

public static boolean collides(AABB a, AABB b)
{
if(Math.abs(a.pos.x - b.pos.x) < a.size.x + b.size.x)
{
if(Math.abs(a.pos.y - b.pos.y) < a.size.y + b.size.y)
{
return true;
}
}

return false;
}

public static boolean inside(AABB a, Vector2Float b)
{
if(Math.abs(a.pos.x - b.x) < a.size.x)
{
if(Math.abs(a.pos.y - b.y) < a.size.y)
{
return true;
}
}
return false;
}
}

``````

And if you don’t have your own implementation or whatever, the simplest possible Vector2Float:

``````
public class Vector2Float
{
public float x, y;
}

``````

The method [icode]collides()[/icode], checks whether 2 AABBs are colliding, and [icode]inside()[/icode], checks whether a point is inside an AABB.

What you must remember, is that unlike most AABB implementations, the pos vector, is the centre of the AABB, and the size vector is half the actual size.

Enjoy!

(And could someone do a performance test with this test vs the normal rectangle collision test? :))

Then rename your fields to `center` and `halfSize`!

Why would I want to do that? I know what they mean. I do what makes sense to me.
If other people want to change the names, then they can. I just notified them of what the fields are.

I like giving my variables misleading names also. To hell with maintenance or readability.

A guy I used to work with wrote super-terse C code, and loved giving all variables 1- or 2-character names. Not always the first letter of the “logical” name of the variable either. “Who cares? I know what the variables are for!” he would say.

Sure, you know what it’s for, but isn’t the whole point of posting the code so other people know and understand the code?

Which is why I added the note at the bottom which started the whole discussion.

There’s kind of a convention of tidying up code and making it readable when it’s offered up to others.

But, whatever.

Storing the center and the extent is (IHMO) the most reasonable. Actually the names are fine as well, I’d probably use ‘center’ and extent or delta…but that’s a different story. But to be useful to others what the variables ‘do’ should be in code block…at least in the form of comments at the decl.