Workshop › Pool › Step 17 of 33
The heart of the game. Split each velocity into a part along the normal and a part across it. When two balls of the same mass collide, they simply swap the parts along the normal; the parts across stay as they were.
```js
// Two balls of the same mass that touch swap the parts of their velocities that point along the line between them.
const along = (a.vx - b.vx) * nx + (a.vy - b.vy) * ny
if (along <= 0) return // already moving apart
a.vx -= along * nx
a.vy -= along * ny
b.vx += along * nx
b.vy += along * ny
```along is how fast a approaches b along the normal: the difference of their velocities, projected on (nx, ny)
with a dot product (x * nx + y * ny).a loses that much along the normal and b gains it: exactly swapping their parts along the line.function collide(a, b) {.collide, under b.y += ny * overlap, write the six lines.Skills: Velocity and gravity, Collision detection
← Balls that touch Six pockets →