Jumping function - height different for framerates

Viewed 130

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.

Jump Image

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;
}
1 Answers
Related