Skip to content

Instantly share code, notes, and snippets.

@17cupsofcoffee
Created September 17, 2019 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 17cupsofcoffee/1eb6b061a9c4b5f9237d25de49c1dc52 to your computer and use it in GitHub Desktop.
Save 17cupsofcoffee/1eb6b061a9c4b5f9237d25de49c1dc52 to your computer and use it in GitHub Desktop.
Splitting animation state from the texture in Tetra
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]
}
}
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