AABB to AABB - Separation

Last time we learned how to check for a collision between two axis aligned rectangles and that collision detection doesnt have to be scary.

First, an optomization:

Thanks to John Blackburne for pointing out a code optomization:

In your code, change any division by 2 to multiplication by .5 (multiplication is faster than division).



Helpful, but...

While having good collision detection is helpful, its not that useful. If you are making a game (especially a platformer), chances are that you need to do something after they collide. You know, something along the lines of separating them so that they DON'T overlap. A character going through the wall or ground isn't my idea of a good game. So lets do something about it!
 
 

AABB to AABB - Detection


Have you ever played a game with bad collision? It's not a very good experience. Bad collision in a game snowballs into other problems. It can interfere with the controls, interfere with the gameplay, and basically anything else that relies on objects overlapping (which is typically a lot). If you are just starting Actionscript, then you are probably using hitTestPoint() or hitTestObject(), flash's built in collision detection. HitTestPoint() tests any given point pixel-perfectly against a graphical object. hitTestObject() uses two graphical objects' bounding boxes to collide.There are pro's and cons with both:

Pros:

hitTestPoint() - Easy to use, and it tests one point pixel perfectly against a graphical object. This can be extremely useful, as it is pixel perfect(meaning it returns true is it is touching any pixel that the object is comprised of).


hitTestObject() - Easy to use is honestly the only thing I can think of. It's pretty crappy otherwise.


Cons:


hitTestPoint - A point is a very small area (obviously). What if you need a bigger area? Using a lot of hitTestPoints will result in a slower program to get the same results as with other methods.

hitTestObject() - You dont get any flexibility with hitTestObject. The bounding boxes are being tested (the boxes who's dimensions are the objects width and height). That means if you dont need that entire area tested, or need more tested, you are out of luck. Not to mention that its a very slow method.


Though theres not really a suitable cure for hitTestPoint() that I can give you, I can give you the cure for hitTestObject!


Now after that very long intro, I can finally say: Welcome to the first of my collision series tutorials: AABB to AABB!