- source code: https://editor.p5js.org/vndrewlee/sketches/_fLSSl1i
This is a code sketch demonstrating collision detection and reflection with linear algebra.
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.
Bouncing dots are created right after the room. The number of dots equals the number of walls of the room.
- 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.