InputTarget.hpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #pragma once
  2. #include <list>
  3. #include <functional>
  4. #include <SFML/Window.hpp>
  5. #include "InputMap.hpp"
  6. template<typename T = int>
  7. class InputTarget
  8. {
  9. public:
  10. using Func = std::function<void(const sf::Event&)>;
  11. InputTarget(const InputTarget<T>&) = delete;
  12. InputTarget<T>& operator=(const InputTarget<T>&) = delete;
  13. InputTarget(const InputMap<T>& map): _inputMap(map) {}
  14. bool think(const sf::Event& event) const
  15. {
  16. for(auto& pair: _eventsPoll)
  17. {
  18. if(_inputMap.get(pair.first) == event)
  19. {
  20. pair.second(event);
  21. return true;
  22. }
  23. }
  24. return false;
  25. }
  26. void think() const
  27. {
  28. for(auto& pair: _eventsRealTime)
  29. {
  30. const Input& input = _inputMap.get(pair.first);
  31. if(input.test())
  32. pair.second(input._event);
  33. }
  34. }
  35. void bind(const T& key, const Func& callback)
  36. {
  37. const Input& input = _inputMap.get(key);
  38. if(input._type & Input::Type::RealTime)
  39. _eventsRealTime.emplace_back(key, callback);
  40. else
  41. _eventsPoll.emplace_back(key, callback);
  42. }
  43. void duoBind(const T& key, const Func& callback)
  44. {
  45. bind(key, callback);
  46. bind(-key, callback);
  47. }
  48. void unbind(const T& key)
  49. {
  50. auto remove_func = [&key](const std::pair<T,Func>& pair) -> bool
  51. {
  52. return pair.first == key;
  53. };
  54. if(_inputMap.get(key)._type & Input::Type::RealTime)
  55. _eventsRealTime.remove_if(remove_func);
  56. else
  57. _eventsPoll.remove_if(remove_func);
  58. }
  59. private:
  60. std::list<std::pair<T, Func>> _eventsRealTime;
  61. std::list<std::pair<T, Func>> _eventsPoll;
  62. const InputMap<T>& _inputMap;
  63. };