gemini_engine/ascii/
animated_sprite.rs

1use super::{Sprite, TextAlign2D};
2use crate::core::{CanDraw, Modifier, Vec2D};
3
4/// The `AnimatedSprite` struct contains a list of `String`s into which it indexes based on its `current_frame` property. You can cycle through frames with the [`AnimatedSprite::next_frame()`](AnimatedSprite::next_frame()) function
5pub struct AnimatedSprite {
6    /// The position from which the animated sprite will be drawn from
7    pub pos: Vec2D,
8    /// A collection of frames - ACII textures to be displayed by the `AnimatedSprite`
9    pub frames: Vec<String>,
10    /// The current frame being displayed. This will index directly into [`frames`](AnimatedSprite::frames)
11    current_frame: usize,
12    /// A raw [`Modifier`], determining the appearance of the `AnimatedSprite`
13    pub modifier: Modifier,
14    /// How the Sprite should align to the position
15    pub align: TextAlign2D,
16}
17
18impl AnimatedSprite {
19    /// Create a new `AnimatedSprite` struct. All newlines at the beginning of each texture will be removed
20    #[must_use]
21    pub fn new(pos: Vec2D, frames: &[&str], modifier: Modifier) -> Self {
22        let processed_frames: Vec<String> = frames
23            .iter()
24            .map(|frame| frame.trim_start_matches('\n').into())
25            .collect();
26
27        Self {
28            pos,
29            frames: processed_frames,
30            current_frame: 0,
31            modifier,
32            align: TextAlign2D::default(),
33        }
34    }
35
36    /// Returns the current frame
37    #[must_use]
38    pub const fn get_current_frame(&self) -> usize {
39        self.current_frame
40    }
41
42    /// Sets the current frame
43    pub fn set_current_frame(&mut self, value: usize) {
44        self.current_frame = value;
45        self.current_frame = self.current_frame.rem_euclid(self.frames.len());
46    }
47
48    /// Go to the next frame of the `AnimatedSprite`'s frames. Will automatically wrap around at the end of the list
49    pub fn next_frame(&mut self) {
50        self.current_frame += 1;
51        if self.current_frame >= self.frames.len() {
52            self.current_frame = 0;
53        }
54    }
55}
56
57impl CanDraw for AnimatedSprite {
58    fn draw_to(&self, canvas: &mut impl crate::core::Canvas) {
59        Sprite::new(self.pos, &self.frames[self.current_frame], self.modifier)
60            .with_align(self.align)
61            .draw_to(canvas);
62    }
63}