Created
September 17, 2019 17:41
-
-
Save 17cupsofcoffee/1eb6b061a9c4b5f9237d25de49c1dc52 to your computer and use it in GitHub Desktop.
Splitting animation state from the texture in Tetra
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tetra::graphics::Rectangle; | |
#[derive(Debug, Clone)] | |
pub struct AnimationState { | |
frames: Vec<Rectangle>, | |
frame_length: i32, | |
current_frame: usize, | |
timer: i32, | |
} | |
impl AnimationState { | |
pub fn new(frames: Vec<Rectangle>, frame_length: i32) -> AnimationState { | |
AnimationState { | |
frames, | |
frame_length, | |
current_frame: 0, | |
timer: 0, | |
} | |
} | |
pub fn tick(&mut self) { | |
self.timer += 1; | |
if self.timer >= self.frame_length { | |
self.current_frame = (self.current_frame + 1) % self.frames.len(); | |
self.timer = 0; | |
} | |
} | |
pub fn current_frame(&self) -> Rectangle { | |
self.frames[self.current_frame] | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod anim_state; | |
use tetra::graphics::{self, Color, DrawParams, Rectangle, Texture}; | |
use tetra::{Context, ContextBuilder, State}; | |
use anim_state::AnimationState; | |
struct GameState { | |
texture: Texture, | |
animation: AnimationState, | |
} | |
impl GameState { | |
fn new(ctx: &mut Context) -> tetra::Result<GameState> { | |
Ok(GameState { | |
texture: Texture::new(ctx, "./tiles.png")?, | |
animation: AnimationState::new( | |
Rectangle::row(0.0, 272.0, 16.0, 16.0).take(8).collect(), | |
5, | |
), | |
}) | |
} | |
} | |
impl State for GameState { | |
fn update(&mut self, _ctx: &mut Context) -> tetra::Result { | |
self.animation.tick(); | |
Ok(()) | |
} | |
fn draw(&mut self, ctx: &mut Context, _dt: f64) -> tetra::Result { | |
graphics::clear(ctx, Color::rgb(0.392, 0.584, 0.929)); | |
graphics::draw( | |
ctx, | |
&self.texture, | |
DrawParams::new().clip(self.animation.current_frame()), | |
); | |
Ok(()) | |
} | |
} | |
fn main() -> tetra::Result { | |
ContextBuilder::new("Hello, world!", 1280, 720) | |
.build()? | |
.run_with(GameState::new) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment