InputTarget.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include <list>
  3. #include <functional>
  4. #include <SFML/Window.hpp>
  5. #include "InputMap.hpp"
  6. #include <iostream>
  7. template<typename T = int>
  8. class InputTarget
  9. {
  10. public:
  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, 1.f);
  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. float power = input.test();
  32. if(power != 0.f)
  33. pair.second(input._event, power);
  34. }
  35. }
  36. void bind(const T& key, const std::function<void(const sf::Event&, float)>& callback)
  37. {
  38. const Input& input = _inputMap.get(key);
  39. if(input._type & Input::Type::RealTime)
  40. _eventsRealTime.emplace_back(key, callback);
  41. else
  42. _eventsPoll.emplace_back(key, callback);
  43. }
  44. void unbind(const T& key)
  45. {
  46. auto remove_func = [&key](const std::pair<T, std::function<void(const sf::Event&, float)>>& pair) -> bool
  47. {
  48. return pair.first == key;
  49. };
  50. if(_inputMap.get(key)._type & Input::Type::RealTime)
  51. _eventsRealTime.remove_if(remove_func);
  52. else
  53. _eventsPoll.remove_if(remove_func);
  54. }
  55. private:
  56. std::list<std::pair<T, std::function<void(const sf::Event&, float power)>>> _eventsRealTime;
  57. std::list<std::pair<T, std::function<void(const sf::Event&, float power)>>> _eventsPoll;
  58. const InputMap<T>& _inputMap;
  59. };