Circle bounce

Set vector, multiply vector, add vector: ingredients to circle bounce (gif)

circle-wall

The golf sample in “Java Game Programming for Dummies” implements a ball resisting friction to a halt, but it’s not as simple as reversing dx and dy as in the square bounce. With a circle boundary, it’s easy to get the ball into a local minima between two points, which is not as realistic.

tempVector.setVec(x - ball.x, y - ball.y); // opposite vector

tempVector.mulVec((hbDist - distIn) / hbDist); // very small!

ball.vel.addVec(tempVector);

The second line, a vector multiplication, multiplies temporary vector dx and dy by 0.034 or so; it’s almost insigificant. I wonder how it could cause such a drastic change. It’s a multiplication of ~ 1/100, or 0.01-magnitude scaling.

Ah, okay. So the ball moves past the boundary in its update, and then I call for the boundary check. Between these calls, the ball is at least one tick past the circle (“a posteriori” collision). In the boundary check method, setVec() flips the vector for me:

ball position  x (boundary) vs. ball.x y (boundary) vs. ball.y
-------------  ----------------------- -----------------------
upper right    x < ball.x              y > ball.y
lower right    x < ball.x              y < ball.y
lower left     x > ball.x              y < ball.y
upper left     x > ball.x              y > ball.y

When the ball is high, its y position is smaller. So the (x – ball.x) and (y – ball.y) expressions flip the sign for us. Convenient.

Once the vector is flipped, we scale it by an infinitesimal amount – just enough to push it back into the boundary. On the next tick, ball update() will properly increment its x and y by the flipped vector, a magnitude in line with what we expect.

This post has been long; the next one will demonstrate this.