From e3fcd5fc180b48e0710fbcbf6cfa94e906b8219c Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sat, 30 Jan 2021 13:03:50 -0500 Subject: Abstracted frame timing stuff --- src/main.cpp | 20 +++++++------------- src/timer.h | 28 ++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 13 deletions(-) create mode 100644 src/timer.h (limited to 'src') diff --git a/src/main.cpp b/src/main.cpp index 1d3d58e..83f63e0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,6 +2,7 @@ #include "renderer.h" #include "game.h" #include "party.h" +#include "timer.h" void loop(Renderer& renderer) { Game game; @@ -18,11 +19,8 @@ void loop(Renderer& renderer) { renderer.render(game); - size_t inputDt = 50; - size_t inputAcc = 0; - - size_t animDt = 1000/5;//30fps * 1000 t/s; - size_t animAcc = 0; + Timer inputTimer(50); + Timer animTimer(1000/5);//30fps * 1000 t/s; size_t lastTime = SDL_GetTicks(); @@ -44,17 +42,13 @@ void loop(Renderer& renderer) { keystate.up = state[SDL_SCANCODE_UP]; keystate.down = state[SDL_SCANCODE_DOWN]; - inputAcc += frameTime; - while (inputAcc > inputDt) { - inputAcc -= inputDt; - + inputTimer.accumulate(frameTime); + while (inputTimer.step()) { party.move(game, keystate); } - animAcc += frameTime; - while (animAcc > animDt) { - animAcc -= animDt; - + animTimer.accumulate(frameTime); + while (animTimer.step()) { game.tickSpriteAnim(); } diff --git a/src/timer.h b/src/timer.h new file mode 100644 index 0000000..0809610 --- /dev/null +++ b/src/timer.h @@ -0,0 +1,28 @@ +#ifndef TIMER_H_45E2F1F9 +#define TIMER_H_45E2F1F9 + +class Timer { +public: + + Timer(int dt) : dt_(dt) {} + + void accumulate(int t) { + acc_ += t; + } + + bool step() { + if (acc_ > dt_) { + acc_ -= dt_; + return true; + } else { + return false; + } + } + +private: + + int dt_; + int acc_ = 0; +}; + +#endif /* end of include guard: TIMER_H_45E2F1F9 */ -- cgit 1.4.1