handle movement events more smoothly

This commit is contained in:
Josh Holtrop 2013-02-18 22:28:34 -05:00
parent ba0fea06fe
commit a29acd2619
2 changed files with 39 additions and 3 deletions

View File

@ -1,4 +1,5 @@
static enum uint TICK_MS = 50; static enum uint TICK_MS = 50;
static enum int MOVE_PER_TICK = 1;
enum enum
{ {
@ -26,16 +27,50 @@ class Game
public: public:
void change_player() void change_player()
{ {
m_pindex = (m_pindex + 1) % 2; m_pindex ^= 1;
} }
void handle_move_event(int type, bool stop) void handle_move_event(int type, bool stop)
{ {
m_players[m_pindex].x += [-10, 10, 0, 0][type]; final switch (type)
m_players[m_pindex].y += [0, 0, 10, -10][type]; {
case MOVE_LEFT:
m_left = !stop;
break;
case MOVE_RIGHT:
m_right = !stop;
break;
case MOVE_UP:
m_up = !stop;
break;
case MOVE_DOWN:
m_down = !stop;
break;
}
}
void update(uint ms)
{
while (ms > (m_last_tick_ms + TICK_MS))
{
if (m_left)
m_players[m_pindex].x -= MOVE_PER_TICK;
if (m_right)
m_players[m_pindex].x += MOVE_PER_TICK;
if (m_up)
m_players[m_pindex].y += MOVE_PER_TICK;
if (m_down)
m_players[m_pindex].y -= MOVE_PER_TICK;
m_last_tick_ms += TICK_MS;
m_tick++;
}
} }
Player[] get_players() { return m_players; } Player[] get_players() { return m_players; }
protected: protected:
bool m_left;
bool m_right;
bool m_up;
bool m_down;
uint m_tick; uint m_tick;
uint m_last_tick_ms;
Player[2] m_players; Player[2] m_players;
int m_pindex; int m_pindex;
}; };

View File

@ -137,6 +137,7 @@ int main(char[][] args)
} }
if (exit) if (exit)
break; break;
game.update(SDL_GetTicks());
display(game); display(game);
} }