简体   繁体   中英

Question about writing gravity code in a 2D game

I'm a beginner and following a tutorial to code flappy bird in android studio. I have 2 questions about the code below. The first frame the bird falls 10 pixels(=GRAVITY). Then the amount of frames is multiplied with the 10 pixels each frame so he falls faster each frame. But what's the use of velocity.scl(1/dt)? It's also possible I understand something wrong? And why does the falling look smooth? I would expect it looked more jarring because the bird moves a lot of pixels each frame.

    if(position.y>0){
        velocity.add(0, GRAVITY, 0); // bird falls 15 pixels above ground
    }

    velocity.scl(dt); //multiply gravity with dt (frame) -> gravity gets larger
    position.add(0, velocity.y, 0);

    if(position.y<0){
        position.y=0; // bird doesn't fall through ground
    }

    velocity.scl(1/dt); // what does this do

Full Bird class:

private static final int GRAVITY = -10;
private Vector3 position;
private Vector3 velocity;
private Texture bird;

public Bird(int x, int y){
    position = new Vector3(x,y,0);
    velocity=new Vector3(0,0,0);
    bird = new Texture("Flappy-midflap.png");
}

public void update(float dt){
    if(position.y>0){
        velocity.add(0, GRAVITY, 0); // bird falls 15 pixels above ground
    }

    velocity.scl(dt); //multiply gravity with dt (frame) -> gravity gets larger
    position.add(0, velocity.y, 0);

    if(position.y<0){
        position.y=0; // bird doesn't fall through ground
    }

    velocity.scl(1/dt); // what does this do
}

public void jump(){
    velocity.y = 250;
}

public Vector3 getPosition() {
    return position;
}

public Texture getTexture() {
    return bird;
}

First of all dt is the delta time rendering first and second frame's rendering time difference. In 1 second this render method executes like 60 times(that means Frame Per Second).

Therefore you should multiply delta with your velocity to smooth movement. Example

First render loop:
Velocity-Y: 250px
dt: 0.018
Result: 4.5px

Second render loop:
Velocity-Y: 240px
dt: 0.025
Result: 4 px

In result this will become 
250 px in 1 second.

If you do not use scale this will become 
First Render Loop: 
Velocity-Y: 250px
dt: 0.018: 
Result: 250px

Second Render Loop:
Velocity-Y: 240px
dt: 0.025
Result: 240px

In result there will be 250 + 240 + .... 10 + 0 px for 1 second

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM