Input.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. if(previous_key_state == KS_RELEASED || previous_key_state == KS_JUST_RELEASED)
  40. resulting_key_state = KS_JUST_PRESSED;
  41. else if(previous_key_state == KS_JUST_PRESSED || previous_key_state == KS_PRESSED)
  42. resulting_key_state = KS_PRESSED;
  43. }
  44. else
  45. {
  46. if(previous_key_state == KS_PRESSED || previous_key_state == KS_JUST_PRESSED)
  47. resulting_key_state = KS_JUST_RELEASED;
  48. else if(previous_key_state == KS_JUST_RELEASED || previous_key_state == KS_RELEASED)
  49. resulting_key_state = KS_RELEASED;
  50. }
  51. key_states[i] = resulting_key_state;
  52. }
  53. }
  54. bool INPUT::key_pressed(Key key)
  55. {
  56. return key_states[key] == KS_JUST_PRESSED;
  57. }
  58. bool INPUT::key_released(Key key)
  59. {
  60. return key_states[key] == KS_JUST_RELEASED;
  61. }
  62. bool INPUT::key_down(Key key)
  63. {
  64. return key_states[key] == KS_JUST_PRESSED || key_states[key] == KS_PRESSED;
  65. }
  66. bool INPUT::key_up(Key key)
  67. {
  68. return key_states[key] == KS_JUST_RELEASED || key_states[key] == KS_RELEASED;
  69. }