Raycasting vs AABB Collision
Detect exact hit points and surface normals using the Slab Method.
How does it work? ↓Raycast against an AABB
Detecting whether a rapidly moving bullet (or a player's line of sight direction vector) hits a wall requires a Raycast. Walls in 2D games are normally represented as Axis-Aligned Bounding Boxes (AABB)—boxes that cannot rotate.
The fastest mathematical way to detect a collision between a Ray and an AABB is the Slab Method.
- The X Slabs: Imagine extending the left and right walls of the box infinitely up and down. We calculate where the ray crosses both of those lines.
- The Y Slabs: We do the exact same thing for the top and bottom walls extended infinitely left and right.
- The Intersection: If the overlapping segment of the X slab intersections overlaps with the Y slab intersections, the ray physically passes through the box!
Why calculate the Surface Normal?
If a bullet hits a wall, you need to know exactly which side of the wall it hit so you can spawn a particle effect pointing outward, or bounce the projectile away. The surface normal is the mathematical vector pointing 90 degrees strictly outward from the face that was struck.
Answers to Common Developer Questions
What is an AABB in game development?
AABB stands for Axis-Aligned Bounding Box. It is a 2D or 3D rectangle whose edges always align exactly with the X and Y coordinate axes, meaning it cannot rotate. Because they never rotate, mathematical collision detection against AABBs is extremely fast and heavily used in rigid body physics engines.
How does the Slab Method work for Raycasting?
The 2D Slab Method calculates where an infinite Ray intersects the horizontal boundaries (the X 'slab') and vertical boundaries (the Y 'slab') of a box. By finding the maximum of the entry distances and the minimum of the exit distances, the algorithm can instantly determine if the 1D intersections overlap, indicating a true 2D hit.
How do you calculate the Surface Normal of an AABB hit?
To find the Surface Normal reflection vector, calculate the exact (X, Y) point of the Raycast hit. Compare that point against the known minimum and maximum X/Y coordinates of the Bounding Box using a small epsilon error margin. Whichever architectural edge the point rests on correlates directly to the Up, Down, Left, or Right normal vector.