Input.cpp 2.3 KB

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