首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于在2D游戏中编写重力代码的问题

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

Stack Overflow用户
提问于 2020-01-29 20:28:54
回答 1查看 172关注 0票数 0

我是一个初学者,正在学习android studio中编写flappy bird的教程。关于下面的代码,我有两个问题。第一帧,鸟下降了10个像素(=重力)。然后将帧的数量乘以每帧的10个像素,这样他每帧下降的速度就会更快。但是velocity.scl(1/dt)有什么用呢?也有可能我理解错了什么?为什么下落看起来很平滑?我希望它看起来更刺耳,因为鸟每一帧都移动了很多像素。

代码语言:javascript
复制
    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类:

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-29 22:01:24

首先,dt是渲染第一帧和第二帧的渲染时间差。在1秒内,这个渲染方法大约执行60次(也就是每秒的帧数)。

因此,你应该用你的速度乘以增量来平滑移动。示例

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59967115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档