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
use std::{cell::RefCell, rc::Rc};
use crate::engine::d2::animation::Ease;
use super::{Behavior, EaseFunction};
struct TweenProps {
elapsed: f32,
from: f32,
to: f32,
duration: f32,
}
pub struct Tween {
props: RefCell<TweenProps>,
easing: EaseFunction,
}
impl Tween {
pub fn new(from: f32, to: f32, seconds: f32, easing: Option<EaseFunction>) -> Self {
let props = RefCell::new(TweenProps {
from,
to,
elapsed: 0.0,
duration: seconds,
});
Self {
props,
easing: easing.unwrap_or(Rc::new(Ease::linear)),
}
}
pub fn elapsed(&self) -> f32 {
self.props.borrow().elapsed
}
}
impl Behavior for Tween {
fn update(&self, dt: f32) -> f32 {
let mut props = self.props.borrow_mut();
props.elapsed += dt;
if props.elapsed >= props.duration {
props.to
} else {
props.from + (props.to - props.from) * (self.easing)(props.elapsed / props.duration)
}
}
fn is_complete(&self) -> bool {
let props = self.props.borrow();
props.elapsed >= props.duration
}
}