我的C++游戏的C++计时器

C++ Timer for my C++ Game

本文关键字:C++ 计时器 游戏 我的      更新时间:2023-10-16

我遇到了一个巨大的问题!我正在制作一款C++僵尸游戏,除了障碍部分,它的效果非常好。我希望僵尸来到屏障,然后让他们等待大约5秒,然后突破屏障。现在我认为你不需要我的整个代码,因为它只是一个计时器,但如果你真的让我知道!基本上,我尝试了很多定时器和睡眠命令,但当我使用它们时,僵尸会停留在屏障上,但其他一切都会冻结,直到定时器出现。例如,如果僵尸在屏障上,而我使用计时器5秒钟,僵尸就会在屏障上停留5秒钟!但其他一切都是如此,其他任何东西都不能移动5秒!他们有没有办法让我只对代码的特定部分使用睡眠命令?这是我用过的为数不多的计时器之一。

int Timer()
{
int s = 0;
int m = 0;
int h = 0;
while (true)
{
    CPos(12,58);
    cout << "Timer: ";
    cout << h/3600 << ":" << m/60 << ":" << s;
    if (s == 59) s = -1;
    if (m == 3599) m = -1;      //3599 = 60*60 -1
    s++;
    m++;
    h++;
    Sleep(1000);
    cout<<"bbb";
}
} 

这一个涉及睡眠命令,我还使用了一个计时器,其中while(number>0)--number,但它有效!但它仍然冻结了我程序中的所有其他内容!

如果你需要什么,请告诉我!

除非EACH僵尸和其他所有程序都在不同的线程上运行,否则调用Sleep将使整个应用程序暂停x毫秒。。。你需要用另一种方式来阻止僵尸,即在时间过去之前不移动他,同时照常更新其他实体(不要使用睡眠)。

编辑:

你不能只创建一个定时器,然后等到定时器完成。当僵尸需要停止移动时,你必须"记住"当前时间,但要继续。然后,每次你再次回到僵尸身上更新它的位置时,你都会检查他是否有暂停计时器。如果他这样做了,那么你必须将你"记住"的时间与当前时间进行比较,并检查他是否停顿了足够长的时间。。。这是一些伪代码:

#include <time>
class Zombie {
private:
  int m_xPos;
  time_t m_rememberedTime;
public:
  Zombie() {
    this->m_xPos = 0;
    this->m_rememberedTime = 0;
  }
  void Update() {
    if (CheckPaused()) {
      // bail out before we move this zombie if he is paused at a barrier.
      return;
    }
    // If it's not paused, then move him as normal.
    this->m_xPos += 1;  // or whatever.
    if (ZombieHitBarrier()) {
      PauseZombieAtBarrier();
    }
  }
  bool CheckPaused() {
    if (this.m_rememberedTime > 0) {
      // If we have a remembered time, calculate the elapsed time.
      time_t currentTime;
      time(&currentTime);
      time_t elapsed = currentTime - this.m_rememberedTime;
      if (elapsed > 5.0f) {
        // 5 seconds has gone by, so clear the remembered time and continue on to return false.
        this.m_rememberedTime = 0;
      } else {
        // 5 seconds has not gone by yet, so return true that we are still paused.
        return true;
      }
    }
    // Either no timer exists, or the timer has just finished, return false that we are not paused.
    return false;
  }
  // Call this when the zombie hits a wall.
  void PauseZombieAtBarrier() {
    // Store the current time in a variable for later use.
    time(&this->m_rememberedTime);
  }
};