base_ui/animation/
animation.rs1use nalgebra_glm as glm;
2
3pub trait Animation {
4 fn update(&mut self, delta_time: f32);
5 fn is_finished(&self) -> bool;
6}
7
8pub struct FadeAnimation {
9 current: f32,
10 start: f32,
11 end: f32,
12 duration: f32,
13 elapsed: f32,
14}
15
16pub struct Vec2Animation {
17 current: glm::Vec2,
18 start: glm::Vec2,
19 end: glm::Vec2,
20 duration: f32,
21 elapsed: f32,
22}
23
24impl FadeAnimation {
25 pub fn new(start: f32, end: f32, duration: f32) -> Self {
26 Self {
27 current: start,
28 start,
29 end,
30 duration,
31 elapsed: 0.0,
32 }
33 }
34
35 pub fn value(&self) -> f32 {
36 self.current
37 }
38}
39
40impl Animation for FadeAnimation {
41 fn update(&mut self, delta_time: f32) {
42 self.elapsed += delta_time;
43 let t = (self.elapsed / self.duration).min(1.0);
44 self.current = self.start + (self.end - self.start) * t;
45 }
46
47 fn is_finished(&self) -> bool {
48 self.elapsed >= self.duration
49 }
50}
51
52impl Vec2Animation {
53 pub fn new(start: glm::Vec2, end: glm::Vec2, duration: f32) -> Self {
54 Self {
55 current: start,
56 start,
57 end,
58 duration,
59 elapsed: 0.0,
60 }
61 }
62
63 pub fn value(&self) -> glm::Vec2 {
64 self.current
65 }
66}
67
68impl Animation for Vec2Animation {
69 fn update(&mut self, delta_time: f32) {
70 self.elapsed += delta_time;
71 let t = (self.elapsed / self.duration).min(1.0);
72 self.current = self.start + (self.end - self.start) * t;
73 }
74
75 fn is_finished(&self) -> bool {
76 self.elapsed >= self.duration
77 }
78}
79
80pub struct AnimationManager {
81 position_animations: Vec<Vec2Animation>,
82 fade_animations: Vec<FadeAnimation>,
83}
84
85impl AnimationManager {
86 pub fn new() -> Self {
87 Self {
88 position_animations: Vec::new(),
89 fade_animations: Vec::new(),
90 }
91 }
92
93 pub fn update(&mut self, delta_time: f32) {
94 self.position_animations.retain_mut(|anim| {
96 anim.update(delta_time);
97 !anim.is_finished()
98 });
99
100 self.fade_animations.retain_mut(|anim| {
101 anim.update(delta_time);
102 !anim.is_finished()
103 });
104 }
105}