Input.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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},
  20. {Key::K_L, Keyboard::Q, Keyboard::A},
  21. {Key::K_R, Keyboard::S},
  22. {Key::K_UP, Keyboard::Up},
  23. {Key::K_DOWN, Keyboard::Down},
  24. {Key::K_LEFT, Keyboard::Left},
  25. {Key::K_RIGHT, Keyboard::Right},
  26. {Key::K_START, Keyboard::Return},
  27. {Key::K_SELECT, Keyboard::BackSpace},
  28. };
  29. void INPUT::key_poll()
  30. {
  31. bool hasFocus = window.hasFocus();
  32. for(unsigned i = 0; i < K_SIZE; i++)
  33. {
  34. bool current_key_state = hasFocus && Keyboard::isKeyPressed(key_map[i].key_code);
  35. KeyState previous_key_state = key_states[i];
  36. KeyState resulting_key_state = KS_RELEASED;
  37. if(current_key_state)
  38. {
  39. switch(current_key_state)
  40. {
  41. case KS_RELEASED:
  42. case KS_JUST_RELEASED:
  43. resulting_key_state = KS_JUST_PRESSED;
  44. break;
  45. case KS_JUST_PRESSED:
  46. case KS_PRESSED:
  47. resulting_key_state = KS_PRESSED;
  48. break;
  49. }
  50. }
  51. else
  52. {
  53. switch(current_key_state)
  54. {
  55. case KS_RELEASED:
  56. case KS_JUST_RELEASED:
  57. resulting_key_state = KS_RELEASED;
  58. break;
  59. case KS_JUST_PRESSED:
  60. case KS_PRESSED:
  61. resulting_key_state = KS_JUST_RELEASED;
  62. break;
  63. }
  64. }
  65. key_states[i] = resulting_key_state;
  66. }
  67. }
  68. bool INPUT::key_pressed(Key key)
  69. {
  70. return key_states[key] == KS_JUST_PRESSED;
  71. }
  72. bool INPUT::key_released(Key key)
  73. {
  74. return key_states[key] == KS_JUST_RELEASED;
  75. }
  76. bool INPUT::key_down(Key key)
  77. {
  78. return key_states[key] == KS_JUST_PRESSED || key_states[key] == KS_PRESSED;
  79. }
  80. bool INPUT::key_up(Key key)
  81. {
  82. return key_states[key] == KS_JUST_RELEASED || key_states[key] == KS_RELEASED;
  83. }