Skip to content

Commit

Permalink
Merge pull request #48 from VictorKoenders/improved_animation
Browse files Browse the repository at this point in the history
Added some utility functions to animations and updated example
  • Loading branch information
17cupsofcoffee committed Dec 21, 2018
2 parents 34091d9 + 332fe28 commit 225fcca
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
20 changes: 19 additions & 1 deletion examples/animation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ extern crate tetra;
use tetra::glm::Vec2;
use tetra::graphics::{self, Animation, Color, DrawParams, Rectangle, Texture};
use tetra::{Context, ContextBuilder, State};
use tetra::input::{self, Key};

struct GameState {
animation: Animation,
Expand All @@ -20,11 +21,28 @@ impl GameState {
),
})
}

pub fn set_animation_1(&mut self,) {
self.animation.set_frames(Rectangle::row(0.0, 272.0, 16.0, 16.0).take(8).collect());
}

pub fn set_animation_2(&mut self,) {
self.animation.set_frames(Rectangle::row(0.0, 256.0, 16.0, 16.0).take(8).collect());
}
}

impl State for GameState {
fn update(&mut self, _ctx: &mut Context) {
fn update(&mut self, ctx: &mut Context) {
self.animation.tick();
if input::is_key_pressed(ctx, Key::Num1) {
self.set_animation_1();
}
if input::is_key_pressed(ctx, Key::Num2) {
self.set_animation_2();
}
if input::is_key_pressed(ctx, Key::Space) {
self.animation.restart();
}
}

fn draw(&mut self, ctx: &mut Context, _dt: f64) {
Expand Down
19 changes: 19 additions & 0 deletions src/graphics/animation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,25 @@ impl Animation {
self.timer = 0;
}
}

/// Set new frames for this animation, while keeping the old texture and frame length. This will reset the current animation.
pub fn set_frames(&mut self, new_frames: Vec<Rectangle>) {
self.frames = new_frames;
self.current_frame = 0;
self.timer = 0;
}

/// Set the new frame length for this animation. This will make the animation run at the new length right away.
/// If you want to reset the animation to 0, call `restart`
pub fn set_frame_length(&mut self, new_frame_length: i32) {
self.frame_length = new_frame_length;
}

/// Will restart the current animation from the beginning.
pub fn restart(&mut self) {
self.current_frame = 0;
self.timer = 0;
}
}

impl Drawable for Animation {
Expand Down

0 comments on commit 225fcca

Please sign in to comment.