As I saw here on this forum, there are couple of posts that are dealing with the Bouncing ball program, where people are posting what they cannot figure out. I'll do the same, but I will also try to hit the core problem of this programming assignment and make the best effort to try to explain what I can't understand, since I am very new at this.
The code in question is from CS106A lectures at Stanford. Here`s the code:
As I can see, from the while loop, the logic is to move the ball, check to see if there is collision with the bottom of the screen, if no, do the pause, in order to get animation effect and continue in this order until you hit the bottom. The moveBall() method tells me, on each iteration, increase ball`s velocity in Y direction (downwards) to get the acceleration effect due to gravity. Now, in order to move the ball, the move() method must be called upon object, that is the ball. move(dx, dy) method, by it`s definition tells: move the object dx and dy pixels from its current position.
Now comes the funky part, as the lecturer of the course mentioned above would say. The checkForCollision() method. If the condition ball.getY() > getHeight() - DIAM_BALL, is true, that means, if I understood correctly that ball is touching the bottom of the screen and the thing that should happen next is bouncing, or simply the ball needs to bounce off the bottom.
So, the process or the action of bouncing, requires the ball to change the direction of the ball, so now the yVel has the negative sign and it (ball) retains 90% of its previous speed. What I don`t understand is how the ball is actually moving upward ? If we look at the moveBall() method, I can see that the effect of moving is happening because of ball.move(xVel, yVel) + the pause(DELEY) in the while loop. But in checkForCollision() method the code defines the necessary Y velocity and its direction in this code line yVel = -yVel * BOUNCE_REDUCE, I don`t see how and where is that yVel implemented ??? I don`t understand the effect of moving upwards! How does the yVel behaves in this program since it is an instance variable ?
One more thing, what tells us how far will the ball bounce, that is how to know when to start falling down again ?