From 60eaa428ac1de92369f98390bed54b512b3a848a Mon Sep 17 00:00:00 2001 From: Xevion Date: Sun, 10 Sep 2023 19:43:09 -0500 Subject: [PATCH] reformat: improve AnimatedTexture API with paused animation abilities --- src/animation.rs | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/animation.rs b/src/animation.rs index cade874..cf7016a 100644 --- a/src/animation.rs +++ b/src/animation.rs @@ -38,11 +38,13 @@ impl<'a> AnimatedTexture<'a> { } } + // Get the current frame number fn current_frame(&self) -> u32 { self.ticker / self.ticks_per_frame } - fn next_frame(&mut self) { + // Move to the next frame. If we are at the end of the animation, reverse the direction + pub fn tick(&mut self) { if self.reversed { self.ticker -= 1; @@ -58,9 +60,14 @@ impl<'a> AnimatedTexture<'a> { } } - fn get_frame_rect(&self) -> Rect { + // Calculate the frame rect (portion of the texture to render) for the given frame. + fn get_frame_rect(&self, frame: u32) -> Rect { + if frame >= self.frame_count { + panic!("Frame {} is out of bounds for this texture", frame); + } + Rect::new( - self.current_frame() as i32 * self.frame_width as i32, + frame as i32 * self.frame_width as i32, 0, self.frame_width, self.frame_height, @@ -73,7 +80,18 @@ impl<'a> AnimatedTexture<'a> { position: (i32, i32), direction: Direction, ) { - let frame_rect = self.get_frame_rect(); + self.render_static(canvas, position, direction, Some(self.current_frame())); + self.tick(); + } + + pub fn render_static( + &mut self, + canvas: &mut Canvas, + position: (i32, i32), + direction: Direction, + frame: Option, + ) { + let frame_rect = self.get_frame_rect(frame.unwrap_or(self.current_frame())); let position_rect = Rect::new( position.0 + self.offset.0, position.1 + self.offset.1, @@ -92,7 +110,5 @@ impl<'a> AnimatedTexture<'a> { false, ) .expect("Could not render texture on canvas"); - - self.next_frame(); } }