Reflection and Collision Detection

Posted on
math for artists linear-algebra

This is a code sketch demonstrating collision detection and reflection with linear algebra.

Room

Every few seconds, a new yellow room is created with 3 to 9 sides. The boundary is represented by an array of vectors.

Each vector is a corner in the room. A blue line is drawn to illustrate each room vector. The yellow lines are segments drawn in between the vectors.

Dots

Bouncing dots are created right after the room. The number of dots equals the number of walls of the room.

Each dot…

  • begins with a random trajectory and speed
  • is given the vectors that make up the room
  • begins near the center of the room, but offset randomly

There is also a drag coefficient gradually reducing the speed of each ball.

Each time a dot crosses a yellow segment, it reflects its angle of travel relative to the segment it has crossed and reverses direction. This happens quickly enough that it appears to bounce off of the walls.