Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用deltaTime产生一致的运动_C++_Game Physics - Fatal编程技术网

C++ 如何使用deltaTime产生一致的运动

C++ 如何使用deltaTime产生一致的运动,c++,game-physics,C++,Game Physics,我想创建一个基于速度的2d游戏。正如当前的代码一样,我使用delta time使速度变化在帧率之间保持一致。然而,当在144hz显示器上运行时,每次跳跃时,跳跃高度都会略有不同(最多相差3个像素,最大高度约为104个像素),但当我切换到60hz时,跳跃高度会立即平均增加约5个像素,最大高度约为109个像素 我已经尝试了许多不同的变量,我应该用delta时间标准化哪些值,但我总是回到这个变量,它最接近我想要的输出 static bool grounded = false; if (!grou

我想创建一个基于速度的2d游戏。正如当前的代码一样,我使用delta time使速度变化在帧率之间保持一致。然而,当在144hz显示器上运行时,每次跳跃时,跳跃高度都会略有不同(最多相差3个像素,最大高度约为104个像素),但当我切换到60hz时,跳跃高度会立即平均增加约5个像素,最大高度约为109个像素

我已经尝试了许多不同的变量,我应该用delta时间标准化哪些值,但我总是回到这个变量,它最接近我想要的输出

static bool grounded = false;  

if (!grounded) {  
    velocity.y += (5000.0f * deltaTime);   //gravity  
}  

if (keys[SPACE_INPUT]) {       //jump command  
    if (grounded) {  
        position.y = 750;  
        velocity.y = -1000.0f;  
        grounded = false;  
    }   
}  

//Used to measure the max height of the jump  
static float maxheight = position.y;  

if (position.y < maxheight) {  
    maxheight = position.y;  
    std::cout << maxheight << std::endl;  
}

//if at the top of the screen  
if (position.y + (velocity.y * deltaTime) < 0) {  
    position.y = 0;  
    velocity.y = 0;  
    grounded = false;  

//if at the bottom of the screen minus sprite height  
} else if (position.y + (velocity.y * deltaTime) >= 800.0f - size.y) {  
    position.y = 800 - size.y;  
    velocity.y = 0;  
    grounded = true;  

//if inside the screen  
} else {  
    grounded = false;  
    position.y += (velocity.y * deltaTime);  
}  
static bool grounded=false;
如果(!接地){
速度.y+=(5000.0f*deltaTime);//重力
}  
if(键[SPACE_INPUT]){//jump命令
如果(接地){
位置y=750;
速度y=-1000.0f;
接地=假;
}   
}  
//用于测量跳跃的最大高度
静态浮动最大高度=位置y;
如果(位置y<最大高度){
最大高度=位置y;

标准::cout公认的技术如下:

// this is in your mainloop, somewhere
const int smallStep = 10;

// deltaTime is a member or global, or anything that retains its value.
deltaTime += (time elapsed since last frame); // the += is important

while(deltaTime > smallStep)
{
    RunPhysicsForTenMillis();
    deltaTime -= smallStep;
}
基本上,你要做的是:每次你开始运行你的物理,你要处理给定数量的步骤,比如10毫秒,加起来就是两帧之间的时间。 runPhysicsForTenMillis()函数将执行与上面类似的操作,但增量时间不变(我建议为10毫秒)

这将为您提供:

  • 决定论。不管你的FPS是什么,物理总是以同样的精确步骤运行
  • 健壮性。如果你有一个长的磁盘访问,或一些流延迟,或任何使一帧更长的东西,你的对象将不会跳入外层空间
  • 在线游戏准备。一旦你进入在线多人游戏,你必须选择一种方法。对于许多技术,如输入传递,小步骤将更容易在线制作