Processing Physics Sim

Viewed 42

I am very new to processing and coding in general. I am trying to make a bit of a physics sim of a ball bouncing with gravity accelerating and decelerating it.

You can see that it works reasonable well on the way down, but then after bouncing it never reaches the top again and I don't understand why. On the way down the speed should be multiplying by gravity, and on the way up it's dividing by gravity. I guess for some reason the code loops faster/more times on the way up and so the speed slows faster. In this sample I was hoping to flip the direction once it hits ypos = 0 again, however I did try instead flipping the direction once ballspeed = very slow and it did a few bounces and got lower and lower each time. Ironically, it behaved more realistically as if there was some loss of energy, but that's not what I want for now since I haven't added any such factor!

void setup(){
  size(500,650);
  background(0);
}

float ballspeed = (0.1);
float ypos = (20);
int direction=(1);
float gravity=(1.098);

void draw(){
  background(0);
  ballmove();
}

void ballmove(){
  stroke(255);
  noFill();
  ellipse(250,ypos,50,50);
  if ( direction == 1){
    ballspeed = ballspeed * gravity;
    ypos = ypos + ballspeed;
  }
  
  if ( direction ==- 1 ){
    ballspeed = ballspeed / gravity;
    ypos = ypos + (ballspeed);
  }

  if ( ypos > 600 ){
    direction =- direction;
    ballspeed =- ballspeed;
  }

  if ( ypos == 0 ){
    ballspeed = 0.1;
    direction =- direction;
  }
}
1 Answers

It's due to the fact that what you're doing here is the Euler's integration and that it's only an approximation of the real world because the timesteps aren't infinitely short. In the real world, the speed and the positon of an object aren't updated every n milliseconds, it happens all the time so with this method, the best you can do is to reduce your timesteps but it will never be perfect.

EDIT : I just noticed that you were multiplying and dividing by the gravity. That's not how physic works: you should just subtract by gravity*timestep since the speed is the antiderivative of the acceleration (which in your case is -gravity). like that your model would be way more realistic and you wouldn't even have to make a difference between the way up and the way down.

In any case, this formula : Ypos = h - g / 2 * (time % sqrt(8 * h / g) - sqrt(2 * h / g)) ^ 2 will give the exact result even if it's not a real sim anymore.

Related