首页 > 解决方案 > 在控制台上调整 2 个不同对象的速度

问题描述

这是一个非常蹩脚的问题,我很抱歉。

标签: c++visual-studioconsole-application

解决方案


你不想使用sleep_for. 它可以睡更长时间,并且不提供时间保证。你想要它一个固定的更新游戏循环。您可以查看流行的游戏引擎以了解它是如何实现的。

但归结为以下伪代码

//mainloop
// get a number of frame based on time.
// take a number of frame higher than expected frame rate. say 10 ms.
int frame = now() / frameDuration; 

while(true)
{
    int frameNow = now() / frameDuration;
    
    while(frame != frameNow)
    {
        Update();
        frame++;
    }

    render();
}

具有以下更新功能:(再次伪代码)

// there, you advance you object for a fixing duration, say 10 ms.
// just use different speed for each
Update()
{
    obstacle.position += obstacleSpeed * frameDuration;
    character.position += characterSpeed * frameDuration;
}

推荐阅读