-
Notifications
You must be signed in to change notification settings - Fork 0
/
tween.hpp
69 lines (60 loc) · 1.96 KB
/
tween.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#define _USE_MATH_DEFINES // For PI
#include <math.h>
class tween {
public:
enum class easing {
linear,
sine_ease_in,
sine_ease_out,
sine_ease_in_out
};
tween(float initial_value, float target_value, int time_ms, easing easing_mode = easing::sine_ease_in_out)
: initial_value(initial_value), target_value(target_value), time_ms(time_ms), easing_mode(easing_mode) {
start_time = std::chrono::high_resolution_clock::now();
current_value = initial_value;
}
~tween() {};
float step() {
auto now = std::chrono::high_resolution_clock::now();
std::chrono::duration<float, std::milli> elapsed = now - start_time;
float t = elapsed.count() / time_ms;
if (t >= 1.0f) {
current_value = target_value;
return current_value;
}
switch (easing_mode) {
case easing::sine_ease_in:
current_value = initial_value + (target_value - initial_value) * sine_ease_in(t);
break;
case easing::sine_ease_out:
current_value = initial_value + (target_value - initial_value) * sine_ease_out(t);
break;
case easing::sine_ease_in_out:
current_value = initial_value + (target_value - initial_value) * sine_ease_in_out(t);
break;
case easing::linear:
default:
current_value = initial_value + (target_value - initial_value) * t;
break;
}
return current_value;
}
public:
float initial_value;
float target_value;
int time_ms;
std::chrono::high_resolution_clock::time_point start_time;
float current_value = 0.f;
easing easing_mode;
private:
float sine_ease_in(float t) {
return -cos(t * M_PI_2) + 1.0f;
}
float sine_ease_out(float t) {
return sin(t * M_PI_2);
}
float sine_ease_in_out(float t) {
return -0.5f * (cos(M_PI * t) - 1.0f);
}
};