Click.
Bam!
BOOM💥
START
Drag the Ray Origin and Aimer to test intersection
Ray Origin: (0.0, 0.0)
Ray Dir: (1.0, 0.0)

Collision: False
Hit Point: ---
Hit Normal: ---
Distance: ---

Code Snippet

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.

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.