use geom::Rectangle;
use graphics::Image;
use std::rc::Rc;
#[derive(Debug)]
struct AnimationData {
frames: Vec<Image>
}
#[derive(Clone, Debug)]
pub struct Animation {
data: Rc<AnimationData>,
current: usize,
current_time: u32,
frame_delay: u32
}
impl Animation {
pub fn new<I>(images: I, frame_delay: u32) -> Animation
where I: IntoIterator<Item = Image> {
let frames = images.into_iter().collect();
Animation {
data: Rc::new(AnimationData { frames }),
current: 0,
current_time: 0,
frame_delay
}
}
pub fn from_spritesheet<R>(sheet: Image, regions: R, frame_delay: u32) -> Animation
where R: IntoIterator<Item = Rectangle> {
Animation::new(regions.into_iter()
.map(|region| sheet.subimage(region)), frame_delay)
}
pub fn tick(&mut self) {
self.current_time += 1;
if self.current_time >= self.frame_delay {
self.current = (self.current + 1) % self.data.frames.len();
self.current_time = 0;
}
}
pub fn current_frame(&self) -> &Image {
&self.data.frames[self.current]
}
}