[英]Question about writing gravity code in a 2D game
我是一名初學者,正在學習在 android studio 中編寫飛揚的小鳥的教程。 我對下面的代碼有兩個問題。 鳥落下的第一幀 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;
}
首先 dt 是渲染第一幀和第二幀的渲染時間差的增量時間。 在 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.