1

Possible Duplicate:
How do I apply gravity to my bouncing ball application?

I have a ball class that bounces off the ground.

Here is a portion of my code:

public void update(){
  yPos += ySpeed;
  ySpeed += gravity;

  if(yPos > BOTTOM_OF_SCREEN){
    ySpeed *= -1;
  }
}

The problem with this code is that when I have a ball in mid air, it bounces higher than it started, and keeps bouncing higher and higher, but I want it to bounce to the same height that it started with.

Community
  • 1
  • 1
user1327446
  • 11
  • 1
  • 3

1 Answers1

3

Do not increase the speed on hitting the bottom (only when it is falling free):

   void update() {
        yPos += ySpeed;

        if (yPos > BOTTOM_OF_SCREEN) {
            ySpeed *= -1;
        } else ySpeed += gravity;
    }
Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55
  • Thanks, but that wasn't the problem. It turns out that I was using Eulers method of numerical integration, which has inaccuracies. In fact, the graph on [Wikipedia article](http://en.wikipedia.org/wiki/Euler_method) illustrates my problem. So it turns out that I have to use a different method (like Verlet integration, which I'm currently trying). – user1327446 Apr 13 '12 at 00:55
  • There was a bug in your code, which I pointed out. Your question was not about realistic ball bouncing. – Eugene Retunsky Apr 13 '12 at 02:04