Skip to content

Commit

Permalink
Refactor animation system
Browse files Browse the repository at this point in the history
  • Loading branch information
PurityLake committed Dec 5, 2023
1 parent 97c40b3 commit 26ffd9f
Showing 1 changed file with 37 additions and 25 deletions.
62 changes: 37 additions & 25 deletions src/animation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{collections::HashMap, time::Duration};

use crate::json::*;
use bevy::{prelude::*, render::view::VisibilitySystems};
use bevy::prelude::*;
use serde::Deserialize;

pub struct AnimationLoadPlugin;
Expand Down Expand Up @@ -42,6 +42,17 @@ pub enum AnimState {
Dead,
}

impl AnimState {
fn should_anim(&self) -> bool {
match self {
AnimState::Walking => true,
AnimState::Dying => true,
AnimState::Flashing => false,
AnimState::Dead => false,
}
}
}

#[derive(Component, Clone, Default)]
pub struct AnimationComponent {
pub walk_handle: Handle<TextureAtlas>,
Expand Down Expand Up @@ -104,13 +115,12 @@ impl Plugin for AnimationLoadPlugin {
)
.add_systems(
Update,
animate_sprite.run_if(state_exists_and_equals(crate::GameState::GamePlay)),
)
.add_systems(PostUpdate, dummy.after(VisibilitySystems::CheckVisibility));
(animate_sprite, flash_sprite)
.run_if(state_exists_and_equals(crate::GameState::GamePlay)),
);
}
}

fn dummy() {}
fn setup(asset_server: Res<AssetServer>, mut anim_list: ResMut<AnimationList>) {
anim_list.handle = asset_server.load("sprites/list.animinfo.json");
}
Expand Down Expand Up @@ -173,21 +183,31 @@ fn load_animations(

fn animate_sprite(
time: Res<Time>,
mut query: Query<(
&mut TextureAtlasSprite,
&mut AnimationComponent,
&mut Visibility,
)>,
mut query: Query<(&mut TextureAtlasSprite, &mut AnimationComponent)>,
) {
for (mut sprite, mut anim, mut visible) in &mut query {
anim.timer.tick(time.delta());
if anim.state == AnimState::Dying && sprite.index == anim.last {
anim.dying_timer.tick(time.delta());
if anim.dying_timer.just_finished() {
anim.state = AnimState::Flashing;
for (mut sprite, mut anim) in &mut query {
if anim.state.should_anim() {
anim.timer.tick(time.delta());
if anim.state == AnimState::Dying && sprite.index == anim.last {
anim.dying_timer.tick(time.delta());
if anim.dying_timer.just_finished() {
anim.state = AnimState::Flashing;
}
continue;
}
if anim.timer.just_finished() {
sprite.index = if sprite.index == anim.last {
anim.first
} else {
sprite.index + 1
};
}
continue;
}
}
}

fn flash_sprite(time: Res<Time>, mut query: Query<(&mut AnimationComponent, &mut Visibility)>) {
for (mut anim, mut visible) in &mut query {
if anim.state == AnimState::Flashing {
anim.flashing_timer.tick(time.delta());
if anim.flashing_timer.just_finished() {
Expand All @@ -201,14 +221,6 @@ fn animate_sprite(
anim.state = AnimState::Dead;
}
}
continue;
}
if anim.timer.just_finished() {
sprite.index = if sprite.index == anim.last {
anim.first
} else {
sprite.index + 1
};
}
}
}

0 comments on commit 26ffd9f

Please sign in to comment.