A dropped ball bouncing straight up and down under the effect of gravity will need two
state variables; one for its height from the floor and one for its velocity (up or down).
Given a position and velocity and a gravitational constant, its position and velocity at the
next time step can be computed using equations from elementary physics. Using standard
physics notation; s stands for position, v for velocity, and a for acceleration. As you
might guess vt is the velocity at time t, vt+1 is the velocity at the next time step. Thus the
transition function may be written as two equations:
st+1 = st + vt
vt+1 = vt + at
So the ball's height at the next time step is just its current height plus its current velocity;
its velocity at the next time step is just its current velocity plus the acceleration due to
gravity.
If you have not studied physics, those equations may seem a bit mysterious; but they are quite simple once you understand them. If a ball is travelling at 10 pixels/step and is currently at location 100, after the next step it will be at 110. In symbols, st = 100, vt = 10, st+1 = st + vt = 100+10 = 110. Velocity is updated similarly.
public Ball(int x, int y, int r, Color c, int vx, int vy) {
this(x,y,r,c);
this.vx = vx;
this.vy = vy;
}
Then you can initialize the ball with:
theBall = new Ball(10,100,20,Color.RED, 2, -20);
For this to work, you must also update the x-coordinate in Ball:step()
2) Add code to keep the Ball in the box. ItŐs just like the bounce code except you must check for hitting the other sides of the box.
3) Add another Ball (or two) going in a different initial direction. Add 5! Hint: ArrayList<Ball>
4) Make them interact. Make them bounce instead of passing through each other. Or, make them repulsive (er, to each other).
4) Make the walls perfectly elastic (so the Balls don't slow down when they bounce. Turn off the gravity. Fun, fun, fun!