Simplify setup_scene_once_loaded in animated_fox (#8999)

# 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.
This commit is contained in:
Nicola Papale 2023-06-29 22:21:07 +02:00 committed by GitHub
parent bcf53b8b5f
commit fd32c6f0ec
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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();