我的C++游戏的C++计时器
C++ Timer for my C++ Game
我遇到了一个巨大的问题!我正在制作一款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(¤tTime);
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);
}
};
相关文章:
- Linux的Cpp上的计时器
- 提升 ASIO 无法识别计时器对象
- 提升 asio 并发计时器取消问题与链
- 使用单体计时器的pthread_cond_timedwait有时会比预期晚超时
- 窗口中的微秒计时器
- 计时器是否从另一个线程启动?
- 如何在 c++ 中创建计时器
- C++回调计时器实现
- 在计时器或主线程外部的命令上销毁/替换线程
- 如何制作每秒从 30 乘 1 倒计时的计时器?
- 保留计时器集合(对象与指针)的最佳方法
- 在网络套接字计时器滴答后增加asio短读错误
- 是否可以仅使用标准 c++/c++11 实现不带"sleep"的计时器?
- 在没有NtSetTimerResolution的Windows上提高计时器分辨率(高分辨率)
- 计时器坏了或者其他什么的
- 功能计时器阻止主功能继续
- IO服务重新启动后,Boost最后期限计时器持续触发
- boost asio计时器是否会在"取消"时阻塞
- Poco 计时器,具有来自同一类的回调
- 使计时器在C++进程中的特定时间关闭,以便同步两个进程