sao-ui-rs/src/anim.rs

75 lines
1.6 KiB
Rust
Raw Normal View History

2022-07-08 19:48:32 +00:00
use keyframe::EasingFunction;
2022-07-09 02:07:19 +00:00
pub struct Animation<F> {
2022-07-08 19:48:32 +00:00
time: f32,
duration: f32,
from: f32,
to: f32,
2022-07-09 02:07:19 +00:00
function: F,
2022-07-08 19:48:32 +00:00
direction: bool,
}
2022-07-09 02:07:19 +00:00
impl<F: EasingFunction> Animation<F> {
pub fn new(function: F, duration: f32, from: f32, to: f32) -> Self {
2022-07-08 19:48:32 +00:00
Self {
2022-07-09 02:07:19 +00:00
time: duration,
duration,
from,
to,
function,
direction: false,
2022-07-08 19:48:32 +00:00
}
}
pub fn update(&mut self, dt: f32) {
self.time += dt;
}
pub fn is_active(&self) -> bool {
2022-07-09 02:07:19 +00:00
self.time < self.duration
2022-07-08 19:48:32 +00:00
}
pub fn get(&self) -> f32 {
2022-07-09 02:07:19 +00:00
if self.is_active() {
let x = self.time / self.duration;
let x = if self.direction { x } else { 1.0 - x };
let lerp = self.function.y(x as f64) as f32;
(1.0 - lerp) * self.from + lerp * self.to
} else if self.direction {
2022-07-08 19:48:32 +00:00
self.to
} else {
2022-07-09 02:07:19 +00:00
self.from
2022-07-08 19:48:32 +00:00
}
}
2022-07-09 02:07:19 +00:00
pub fn ease_to(&mut self, duration: f32, to: f32) {
2022-07-08 19:48:32 +00:00
self.from = self.get();
self.to = to;
self.time = 0.0;
self.duration = duration;
2022-07-09 02:07:19 +00:00
self.direction = true;
}
pub fn ease_in(&mut self) {
if !self.direction {
self.ease_toggle();
}
}
pub fn ease_out(&mut self) {
if self.direction {
self.ease_toggle();
}
}
pub fn ease_toggle(&mut self) {
if self.is_active() {
self.time = self.duration - self.time;
} else {
self.time = 0.0;
}
self.direction = !self.direction;
2022-07-08 19:48:32 +00:00
}
}