Input.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "Input.h"
  2. #include "Graphics.h" // window
  3. #include "sfwindow.h"
  4. #include <SFML/Window/Keyboard.hpp>
  5. #include <SFML/Window.hpp>
  6. #define INPUT WalrusRPG::Input
  7. using WalrusRPG::Input::Key;
  8. using WalrusRPG::Input::KeyState;
  9. using sf::Keyboard;
  10. struct InputMap
  11. {
  12. Key key;
  13. sf::Keyboard::Key key_code;
  14. sf::Keyboard::Key key_code_alt;
  15. };
  16. KeyState key_states[Key::K_SIZE] = {KeyState::KS_RELEASED};
  17. InputMap key_map[] = {
  18. {Key::K_A, Keyboard::W, Keyboard::Z},
  19. {Key::K_B, Keyboard::X, Keyboard::Unknown},
  20. {Key::K_L, Keyboard::Q, Keyboard::A},
  21. {Key::K_R, Keyboard::S, Keyboard::Unknown},
  22. {Key::K_UP, Keyboard::Up, Keyboard::Unknown},
  23. {Key::K_DOWN, Keyboard::Down, Keyboard::Unknown},
  24. {Key::K_LEFT, Keyboard::Left, Keyboard::Unknown},
  25. {Key::K_RIGHT, Keyboard::Right, Keyboard::Unknown},
  26. {Key::K_START, Keyboard::Return, Keyboard::Unknown},
  27. {Key::K_SELECT, Keyboard::BackSpace, Keyboard::Unknown},
  28. };
  29. KeyState INPUT::key_get_state(Key key)
  30. {
  31. return key_states[key];
  32. }
  33. void INPUT::key_poll()
  34. {
  35. bool hasFocus = window.hasFocus();
  36. for (unsigned i = 0; i < K_SIZE; i++)
  37. {
  38. bool current_key_state = hasFocus && Keyboard::isKeyPressed(key_map[i].key_code);
  39. KeyState previous_key_state = key_states[i];
  40. KeyState resulting_key_state = KS_RELEASED;
  41. if (current_key_state)
  42. {
  43. if (previous_key_state == KS_RELEASED ||
  44. previous_key_state == KS_JUST_RELEASED)
  45. resulting_key_state = KS_JUST_PRESSED;
  46. else if (previous_key_state == KS_JUST_PRESSED ||
  47. previous_key_state == KS_PRESSED)
  48. resulting_key_state = KS_PRESSED;
  49. }
  50. else
  51. {
  52. if (previous_key_state == KS_PRESSED || previous_key_state == KS_JUST_PRESSED)
  53. resulting_key_state = KS_JUST_RELEASED;
  54. else if (previous_key_state == KS_JUST_RELEASED ||
  55. previous_key_state == KS_RELEASED)
  56. resulting_key_state = KS_RELEASED;
  57. }
  58. key_states[i] = resulting_key_state;
  59. }
  60. }
  61. bool INPUT::key_pressed(Key key)
  62. {
  63. return key_states[key] == KS_JUST_PRESSED;
  64. }
  65. bool INPUT::key_released(Key key)
  66. {
  67. return key_states[key] == KS_JUST_RELEASED;
  68. }
  69. bool INPUT::key_down(Key key)
  70. {
  71. return key_states[key] == KS_JUST_PRESSED || key_states[key] == KS_PRESSED;
  72. }
  73. bool INPUT::key_up(Key key)
  74. {
  75. return key_states[key] == KS_JUST_RELEASED || key_states[key] == KS_RELEASED;
  76. }