bevy_animator/state.rs
1//=================================================================================
2// Animation State is a trait that allows you to define functionality that will allow
3// the state of an animation to be updated based on the world.
4//=================================================================================
5
6use std::marker::PhantomData;
7use bevy::{ecs::query::{ReadOnlyQueryData, WorldQuery}, prelude::*};
8use crate::animation::{update_animators, Animation, Animator};
9
10//=================================================================================
11// AnimationState Plugin
12//=================================================================================
13
14pub struct AnimationStatePlugin<A : AnimationState>(PhantomData<A>);
15
16impl <A : AnimationState + Send + Sync + 'static> Default for AnimationStatePlugin<A> {
17 fn default() -> Self {
18 AnimationStatePlugin(PhantomData)
19 }
20}
21
22impl <A : AnimationState + Send + Sync + 'static> Plugin for AnimationStatePlugin<A> {
23 fn build(&self, app: &mut App) {
24 app
25 .add_systems(PostUpdate, update_states::<A>.before(update_animators::<A>))
26 ;
27 }
28}
29
30//=================================================================================
31// AnimationState Systems
32//=================================================================================
33
34
35pub(crate) fn update_states<A : AnimationState + Send + Sync + 'static>(
36 mut states : Query<(&mut Animator<A>, A::StateQuery<'_, '_>)>,
37) {
38 for (mut state, item) in states.iter_mut() {
39 A::update_state(state.as_mut(), &item);
40 }
41}
42
43//=================================================================================
44// Animation State
45//=================================================================================
46
47/// This trait is used to allow animations to update their state based on the compenent the animation is attached to.
48pub trait AnimationState : Animation {
49
50 /// The query that will allow the animation to read data from the component it is attached to.
51 type StateQuery<'w, 's> : ReadOnlyQueryData;
52
53 /// This method will update the state of the animation based on the data from the component it is attached to.
54 fn update_state(animator : &mut Animator<Self>, data : & <Self::StateQuery<'_, '_> as WorldQuery>::Item<'_>);
55}