use std::time::Duration;
use crate::graphics::texture::Texture;
use crate::graphics::{DrawParams, Rectangle};
use crate::time;
use crate::Context;
#[derive(Debug, Clone)]
pub struct Animation {
texture: Texture,
frames: Vec<Rectangle>,
frame_length: Duration,
current_frame: usize,
timer: Duration,
repeating: bool,
}
impl Animation {
pub fn new(texture: Texture, frames: Vec<Rectangle>, frame_length: Duration) -> Animation {
Animation {
texture,
frames,
frame_length,
current_frame: 0,
timer: Duration::from_secs(0),
repeating: true,
}
}
pub fn once(texture: Texture, frames: Vec<Rectangle>, frame_length: Duration) -> Animation {
Animation {
texture,
frames,
frame_length,
current_frame: 0,
timer: Duration::from_secs(0),
repeating: false,
}
}
pub fn draw<P>(&self, ctx: &mut Context, params: P)
where
P: Into<DrawParams>,
{
let frame = self.frames[self.current_frame];
self.texture.draw_region(ctx, frame, params);
}
pub fn advance(&mut self, ctx: &Context) {
self.advance_by(time::get_delta_time(ctx));
}
pub fn advance_by(&mut self, duration: Duration) {
self.timer += duration;
let frames_remaining = self.has_frames_remaining();
if frames_remaining || self.repeating {
while self.timer >= self.frame_length {
self.current_frame = (self.current_frame + 1) % self.frames.len();
self.timer -= self.frame_length;
}
} else if self.timer > self.frame_length {
self.timer = self.frame_length;
}
}
pub fn restart(&mut self) {
self.current_frame = 0;
self.timer = Duration::from_secs(0);
}
pub fn texture(&self) -> &Texture {
&self.texture
}
pub fn set_texture(&mut self, texture: Texture) {
self.texture = texture;
}
pub fn frames(&self) -> &[Rectangle] {
&self.frames
}
pub fn set_frames(&mut self, new_frames: Vec<Rectangle>) {
self.frames = new_frames;
self.restart();
}
pub fn frame_length(&self) -> Duration {
self.frame_length
}
pub fn set_frame_length(&mut self, new_frame_length: Duration) {
self.frame_length = new_frame_length;
}
pub fn repeating(&self) -> bool {
self.repeating
}
pub fn set_repeating(&mut self, repeating: bool) {
self.repeating = repeating;
}
pub fn current_frame_index(&self) -> usize {
self.current_frame
}
pub fn set_current_frame_index(&mut self, index: usize) {
assert!(index < self.frames.len());
self.current_frame = index;
}
pub fn current_frame_time(&self) -> Duration {
self.timer
}
pub fn set_current_frame_time(&mut self, duration: Duration) {
self.timer = duration;
}
pub fn is_finished(&self) -> bool {
!self.repeating && !self.has_frames_remaining()
}
pub fn has_frames_remaining(&self) -> bool {
self.current_frame < self.frames.len() - 1
}
}