For a Jump'n'Run game, I'm trying to make a jump and I found this function. The Problem is that the framerate (time_diff) is different on systems so sometimes it as example 1 and sometimes it is 10.
Now this function will cause my character jump different heights based on the frame rate
public void jump() {
ySpeed = -100;
}
// time_diff is time difference between this and last frame
public void update(double time_diff) {
y = y - ySpeed * time_diff;
ySpeed = ySpeed + 9.81 * time_diff;
}
Here is also an example of frame rate 4 and 20 (the values are not exact because I divided them by 20), but you see that the with frame rate 20 it jumps higher (and further) as with frame rate 4.
So how can I archive it that the jumping height is always constant no matter what the framerate is?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Edit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
I solved it like this whith the help of luk2302:
double remaining_time = 0;
final double step_size = 4;
public void jump() {
ySpeed = -100;
}
// time_diff is time difference between this and last frame
public void update(double time_diff) {
remaining_time += time_diff;
while (remaining_time >= step_size) {
update_helper(step_size);
remaining_time -= step_size;
}
}
public void update_helper(double time_diff) {
y = y - ySpeed * time_diff;
ySpeed = ySpeed + 9.81 * time_diff;
}
Key point: the frame rate must never ever have any impact on the physics calculation.
What you should do is decide on a fixed step size for physics steps like 1/100 of a second. Then you always perform only those steps, nothing more, nothing less. Accumulate time until you have reached the step offset and do more than one step if you have accumulated too much time:
double remaining_time;
final double step_size;
public void update(double diff) {
remaining_time += diff;
while (remaining_time >= step_size) {
step(step_size); // perform your actual physics logic
remaining_time -= step_size;
}
}
If you change the step_size
the calculation changes, but that is just how your game decides physics work - the key is that the value is fixed across all clients that run the same game.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With