有关在2D游戏中编写重力代码的问题

我是一个初学者,正在关注android studio中编写飞扬的小鸟的教程。我对以下代码有2个问题。鸟的第一帧下降10像素(= GRAVITY)。然后,将帧数量乘以每帧10个像素,这样他每帧下降得更快。但是,velocity.scl(1 / 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

全鸟类:

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);
    bird = new Texture("flappy-midflap.png");
}

public void update(float dt){
    if(position.y>0){
        velocity.add(0,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;
}
xpniree 回答:有关在2D游戏中编写重力代码的问题

首先dt是渲染第一帧和第二帧的渲染时间差的增量时间。在1秒钟内,此render方法执行了60次(即每秒帧)。

因此,应将增量乘以速度,以使运动平稳。 例子

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
本文链接:https://www.f2er.com/2691858.html

大家都在问