Skip to content

Commit

Permalink
Simplify setup_scene_once_loaded in animated_fox (#8999)
Browse files Browse the repository at this point in the history
# Objective

The setup code in `animated_fox` uses a `done` boolean to avoid running
the `play` logic repetitively.

It is a common pattern, but it just work with exactly one fox, and
misses an even more common pattern.

When a user modifies the code to try it with several foxes, they are
confused as to why it doesn't work (#8996).

## Solution

The more common pattern is to use `Added<AnimationPlayer>` as a query
filter.

This both reduces complexity and naturally extend the setup code to
handle several foxes, added at any time.
  • Loading branch information
nicopap authored Jun 29, 2023
1 parent bcf53b8 commit fd32c6f
Showing 1 changed file with 5 additions and 9 deletions.
14 changes: 5 additions & 9 deletions examples/animation/animated_fox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,24 +83,20 @@ fn setup(
// Once the scene is loaded, start the animation
fn setup_scene_once_loaded(
animations: Res<Animations>,
mut player: Query<&mut AnimationPlayer>,
mut done: Local<bool>,
mut players: Query<&mut AnimationPlayer, Added<AnimationPlayer>>,
) {
if !*done {
if let Ok(mut player) = player.get_single_mut() {
player.play(animations.0[0].clone_weak()).repeat();
*done = true;
}
for mut player in &mut players {
player.play(animations.0[0].clone_weak()).repeat();
}
}

fn keyboard_animation_control(
keyboard_input: Res<Input<KeyCode>>,
mut animation_player: Query<&mut AnimationPlayer>,
mut animation_players: Query<&mut AnimationPlayer>,
animations: Res<Animations>,
mut current_animation: Local<usize>,
) {
if let Ok(mut player) = animation_player.get_single_mut() {
for mut player in &mut animation_players {
if keyboard_input.just_pressed(KeyCode::Space) {
if player.is_paused() {
player.resume();
Expand Down

0 comments on commit fd32c6f

Please sign in to comment.