Question

Hey I am trying to figure out the best way to implement gravity in my program that is simply a ball bouncing. The program uses a method that is called 50 times a second (the rate at which the gametimer ticks) and in this method I call the gravity method. In the gravity method I currently have

public void Gravity(){
   this.currentPositionY = this.currentPositionY + 9;
   if (this.currentPositionY >= 581){
      this.currentPositionY=581;
     }
}

Problems with my code: In gravity velocity is not constant it varies with the time, but I am unsure of how to implement time with the gravity method being called so often. Also currently I have it so that the ball stops at 581, so that it does not fall through the screen. How would I implement a bounce that is higher when the ball falls for longer and shorter when the ball falls less? Thanks for your time!

Was it helpful?

Solution

Have a variable outside of the method for its y-velocity. Every tick, increase its velocity accounting for gravity.
If the ball is past a boundary, set it to the boundary and set the velocity to -1*velocity to make it "bounce" in the other direction.

Maybe something like this:

private int currentVelocityY = 0;
private int gravity = 3;
public void Gravity(){
    this.currentPositionY = this.currentPositionY + this.currentVelocityY;
    if (this.currentPositionY >= 581){
        this.currentPositionY=581;
        this.currentVelocityY = -1 * this.currentVelocityY;
    }
    currentVelocityY = currentVelocityY + gravity;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top