【问题标题】:Question about writing gravity code in a 2D game关于在2D游戏中写重力代码的问题
【发布时间】:2020-05-14 22:51:34
【问题描述】:

我是一名初学者,正在学习在 android studio 中编写 flappy bird 的教程。我对下面的代码有 2 个问题。鸟落下的第一帧 10 像素(=重力)。然后将帧数乘以每帧 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,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;
}

【问题讨论】:

  • Vector3.scl(float) - “用一个标量缩放这个向量”。它基本上将所有值乘以该值。 dt 通常代表增量时间 - 自上次更新以来的时间差。因此,如果更新需要 40 毫秒,则将向量乘以 40/1000。这就是移动如此之低的原因,它不是每帧 10 像素,而是其中的一小部分。

标签: java android-studio libgdx game-physics 2d-games


【解决方案1】:

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

因此,您应该将 delta 与您的速度相乘以平滑移动。 示例

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    相关资源
    最近更新 更多