Skip to content

Reflection (bounce off a surface)

Reflection (bounce off a surface)

function reflect(direction, normal):
    // direction: incoming velocity vector
    // normal: unit vector perpendicular to the surface, pointing outward
    d = dot(direction, normal)
    return direction - scale(normal, 2 * d)

Reflection uses the formula r = d - 2(d·n)n, derived from vector projection. The term (d·n)n is the component of the direction vector that lies along the normal — i.e., how much of the motion is heading into the surface. Subtracting twice that component flips just that piece, leaving the component parallel to the surface untouched. This is the same math used for light bouncing off a mirror, hence "reflection."