c++ - 在按键之间添加延迟

标签 c++

我正在使用 GetAsyncKeyState() 为我制作的游戏获取每一帧的输入。

我想在每次按下时移动一个 x,但不是每一帧,必须有延迟。我目前正在通过每次按下按键时冷却下来来做到这一点。

这是我的 CoolDown 类的一些部分:

bool test(bool asumedStatus)
{
    if(asumedStatus == status)
    {
        return true;
    } else
    {
        return false;
    }
}

void go()
{
    if(currentCount == runFor)
    {
        status = OFF_COOLDOWN;
    } else
    {
        currentCount++;
    }
}

void start()
{
    currentCount = 0;
    status = ON_COOLDOWN;
}

controls 每帧都会被调用以获取用户输入

void controls()
{
    if(test(OFF_COOLDOWN))
    {
        if(KEY_L && !KEY_R && !KEY_U && !KEY_D)
        {
            left();
            print();
            cd.start();
        }
        else if(KEY_R && !KEY_L && !KEY_D && !KEY_U)
        {
            right();
            print();
            cd.start();
        } else if(KEY_U && !KEY_L && !KEY_D && !KEY_R)
        {
            up();
            print();
            cd.start();
        } else if(KEY_D && !KEY_L && !KEY_R && !KEY_U)
        {
            down();
            print();
            cd.start();
        }
    } else
    {
        cd.go();
    }
}

不幸的是,这不起作用,没有延迟。什么都没有改变。

有人知道我如何完成这个吗?

最佳答案

这是我的做法:


我用时间来表示帧或游戏的滴答声。

我会制作 2 个变量:

  • startTime - 延迟开始的时间点
  • currentTime - 当前时间

现在,每次报价,我都会更新 currentTime(按 1)。

通过计算这些变量之间的差异,您可以获得自延迟开始以来耗时。

如果差异大于 delay,那么我必须重置变量,重新开始。因此,将 startTime 设置为 currentTime,并将 currentTime 设置为 0

如果差异小于 delay,什么也不做,因为延迟没有“完成”。

类似于:

startTime = 0;
currentTime = 0;
delay = 2000; //In frames/ticks

//Called every frame/tick
void update() {
    ++currentTime; //Update time

    if (currentTime - startTime > delay) {
        //Reset
        startTime = currentTime;
        currentTime = 0;

        //Update whatever requires a delay
    }
}

关于c++ - 在按键之间添加延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38255895/

相关文章:

c++ - 优先约束背包

c++ - 如何在 Boost Asio 上组合链包装器和优先包装器

c++ - OpenCV检测运动

c++ - std::system 或 exec 是更好的做法吗?

c++ - 在没有 const 的情况下将 shared_ptr<Derived>& 作为 shared_ptr<Base>& 传递时出错

c++ - 如何访问 C++ 中的特定范围?

c++ - 将字符串写入指针 C++

c++ - 序列化结构并使用 C++ 通过套接字发送它

c++ - 自适应正交 (C++)

c++ - 如何获得对操作数的引用?