C++打地鼠游戏开发:如何实现mole1 sprite每3秒显示
Hey there! Let's figure out how to get that mole popping up every 3 seconds without relying on the chrono library. Since you already got the first display working, we just need to add a reliable timing loop that fits your game's setup.
核心思路:用时间累计变量替代chrono
Instead of using chrono, we can track time using a simple accumulator variable that adds up the time passed each frame in your game loop. When this accumulator hits 3 seconds, we trigger the mole to show up, then reset the accumulator to start counting again.
伪代码实现(通用游戏框架)
Here's a straightforward example you can adapt to your codebase:
// 定义全局/类成员变量,用来追踪时间 float timeSinceLastMole = 0.0f; const float MOLE_SPAWN_INTERVAL = 3.0f; // 每3秒触发一次 bool isGameRunning = true; float totalGameTime = 5.0f; // 当前5秒,后续改成60即可 float elapsedGameTime = 0.0f; // 主游戏循环 while (isGameRunning) { // 获取当前帧与上一帧的时间差(单位:秒) float deltaTime = getDeltaTime(); // 先处理游戏时长结束的逻辑 elapsedGameTime += deltaTime; if (elapsedGameTime >= totalGameTime) { isGameRunning = false; break; } // 处理地鼠定时显示 timeSinceLastMole += deltaTime; if (timeSinceLastMole >= MOLE_SPAWN_INTERVAL) { mole1.visible = true; // 如果你想让地鼠显示几秒后自动隐藏,可以加个隐藏定时器 // hideMoleTimer = 0.8f; // 比如显示0.8秒后隐藏 timeSinceLastMole -= MOLE_SPAWN_INTERVAL; // 重置定时器,避免跳过间隔 } // (可选)地鼠自动隐藏逻辑 // if (hideMoleTimer > 0) { // hideMoleTimer -= deltaTime; // if (hideMoleTimer <= 0) { // mole1.visible = false; // } // } // 其他游戏逻辑:输入处理、渲染等 handlePlayerInput(); renderGame(); }
如何实现getDeltaTime()(不用chrono)
Depending on what library you're using for your game, here are a few simple ways to get the frame time:
- SDL 2: Use
SDL_GetTicks()to track frame timeUint32 lastFrameTick = SDL_GetTicks(); float getDeltaTime() { Uint32 currentTick = SDL_GetTicks(); float delta = (currentTick - lastFrameTick) / 1000.0f; lastFrameTick = currentTick; return delta; } - SFML: Use
sf::Clockfor precise time trackingsf::Clock frameClock; sf::Time lastFrameTime = frameClock.getElapsedTime(); float getDeltaTime() { sf::Time currentTime = frameClock.getElapsedTime(); float delta = (currentTime - lastFrameTime).asSeconds(); lastFrameTime = currentTime; return delta; } - 基础控制台/自定义窗口: Use the C standard library's
time()function (lower precision, but works for simple games)time_t lastFrameTime = time(nullptr); float getDeltaTime() { time_t currentTime = time(nullptr); float delta = difftime(currentTime, lastFrameTime); lastFrameTime = currentTime; return delta; }
额外提示
- If you're using a fixed-frame-rate setup (e.g., 30 FPS), you could also use frame counts instead: trigger the mole every 90 frames (30 frames/sec × 3 sec). Just note that this will be less accurate if your frame rate drops.
- Once you get this working for mole1, you can replicate the logic for the other 5 moles—just give each its own
timeSinceLastSpawnvariable and adjust intervals if you want them to pop up at different times.
内容的提问来源于stack exchange,提问作者element

