NasNas
An intuitive and beginner friendly 2D game framework for C++
tween/Tween.hpp
1 // Created by Modar Nasser on 17/07/2021.
2 
3 #pragma once
4 
5 #include <functional>
6 #include <vector>
7 
8 #include <SFML/System/Clock.hpp>
9 
10 #include <NasNas/tween/Easing.hpp>
11 
12 namespace ns {
13 
14  class Tween {
15  public:
16  explicit Tween() = default;
17 
18  void clear();
19 
20  auto loop() -> Tween&;
21 
22  auto after(float delay) -> Tween&;
23 
24  auto from_to(float start, float end) -> Tween&;
25 
26  auto to(float end) -> Tween&;
27 
28  auto during(float duration) -> Tween&;
29 
30  auto apply(tween::CallbackFunction callback) -> Tween&;
31 
32  auto with(tween::EasingFunction function) -> Tween&;
33 
34  auto delay(float delay) -> Tween&;
35 
36  void onEnd(std::function<void()> fn);
37 
38  void restart();
39 
40  auto ended() const -> bool;
41 
42  auto step() -> float;
43 
44  private:
45  sf::Clock m_clock;
46  std::vector<float> m_starts;
47  std::vector<float> m_ends;
48  std::vector<float> m_durations = {1.f};
49  std::vector<float> m_delays = {0.f};
50  std::vector<tween::EasingFunction> m_easing_fns = {easing::linear};
51  std::vector<tween::CallbackFunction> m_on_step_cbs = {[](float){}};
52  std::function<void()> m_on_end_cb = []{};
53  unsigned m_index = 0;
54  float m_initial_delay = 0.f;
55  float m_current_delay = 0.f;
56  bool m_first_run = true;
57  bool m_on_end_called = false;
58  bool m_loop = false;
59 
60  inline auto interpolate(unsigned i, float x) const -> float {
61  return (m_ends[i] - m_starts[i]) * x + m_starts[i];
62  };
63 
64  void emplaceAnimation();
65  };
66 
67 }