summary refs log tree commit diff stats
path: root/src/input_system.cpp
blob: 54a291cb7498b29dc2dfc26d9569942ed9833739 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "input_system.h"
#include "game.h"
#include "character_system.h"

struct Input {
  bool left = false;
  bool right = false;
  bool up = false;
  bool down = false;
};

void InputSystem::tick(double dt) {
  SDL_Event e;
  while (SDL_PollEvent(&e)) {
    if (e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {
      game_.quit();

      return;
    } else if (e.type == SDL_KEYDOWN && (e.key.keysym.sym == SDLK_LSHIFT || e.key.keysym.sym == SDLK_RSHIFT)) {
      for (int spriteId : game_.getSprites()) {
        Sprite& sprite = game_.getSprite(spriteId);
        if (sprite.controllable) {
          game_.getSystem<CharacterSystem>().beginCrouch(spriteId);
        }
      }
    } else if (e.type == SDL_KEYUP && (e.key.keysym.sym == SDLK_LSHIFT || e.key.keysym.sym == SDLK_RSHIFT)) {
      for (int spriteId : game_.getSprites()) {
        Sprite& sprite = game_.getSprite(spriteId);
        if (sprite.controllable) {
          game_.getSystem<CharacterSystem>().endCrouch(spriteId);
        }
      }
    }
  }

  Input keystate;
  const Uint8* state = SDL_GetKeyboardState(NULL);
  keystate.left = state[SDL_SCANCODE_LEFT];
  keystate.right = state[SDL_SCANCODE_RIGHT];
  keystate.up = state[SDL_SCANCODE_UP];
  keystate.down = state[SDL_SCANCODE_DOWN];

  for (int spriteId : game_.getSprites()) {
    Sprite& sprite = game_.getSprite(spriteId);

    if (sprite.controllable) {
      bool directed = false;
      Direction dir = Direction::left;

      if (keystate.up)
      {
        directed = true;
        dir = Direction::up;
      } else if (keystate.down)
      {
        directed = true;
        dir = Direction::down;
      }

      if (keystate.left)
      {
        directed = true;
        if (dir == Direction::up) {
          dir = Direction::up_left;
        } else if (dir == Direction::down) {
          dir = Direction::down_left;
        } else {
          dir = Direction::left;
        }
      } else if (keystate.right)
      {
        directed = true;
        if (dir == Direction::up) {
          dir = Direction::up_right;
        } else if (dir == Direction::down) {
          dir = Direction::down_right;
        } else {
          dir = Direction::right;
        }
      }

      if (directed) {
        game_.getSystem<CharacterSystem>().moveInDirection(spriteId, dir);
      } else {
        game_.getSystem<CharacterSystem>().stopDirecting(spriteId);
      }
    }
  }
}