bevy/examples/2d/sprite_animation.rs
Carter Anderson 015f2c69ca
Merge Style properties into Node. Use ComputedNode for computed properties. (#15975)
# Objective

Continue improving the user experience of our UI Node API in the
direction specified by [Bevy's Next Generation Scene / UI
System](https://github.com/bevyengine/bevy/discussions/14437)

## Solution

As specified in the document above, merge `Style` fields into `Node`,
and move "computed Node fields" into `ComputedNode` (I chose this name
over something like `ComputedNodeLayout` because it currently contains
more than just layout info. If we want to break this up / rename these
concepts, lets do that in a separate PR). `Style` has been removed.

This accomplishes a number of goals:

## Ergonomics wins

Specifying both `Node` and `Style` is now no longer required for
non-default styles

Before:
```rust
commands.spawn((
    Node::default(),
    Style {
        width:  Val::Px(100.),
        ..default()
    },
));
```

After:

```rust
commands.spawn(Node {
    width:  Val::Px(100.),
    ..default()
});
```

## Conceptual clarity

`Style` was never a comprehensive "style sheet". It only defined "core"
style properties that all `Nodes` shared. Any "styled property" that
couldn't fit that mold had to be in a separate component. A "real" style
system would style properties _across_ components (`Node`, `Button`,
etc). We have plans to build a true style system (see the doc linked
above).

By moving the `Style` fields to `Node`, we fully embrace `Node` as the
driving concept and remove the "style system" confusion.

## Next Steps

* Consider identifying and splitting out "style properties that aren't
core to Node". This should not happen for Bevy 0.15.

---

## Migration Guide

Move any fields set on `Style` into `Node` and replace all `Style`
component usage with `Node`.

Before:
```rust
commands.spawn((
    Node::default(),
    Style {
        width:  Val::Px(100.),
        ..default()
    },
));
```

After:

```rust
commands.spawn(Node {
    width:  Val::Px(100.),
    ..default()
});
```

For any usage of the "computed node properties" that used to live on
`Node`, use `ComputedNode` instead:

Before:
```rust
fn system(nodes: Query<&Node>) {
    for node in &nodes {
        let computed_size = node.size();
    }
}
```

After:
```rust
fn system(computed_nodes: Query<&ComputedNode>) {
    for computed_node in &computed_nodes {
        let computed_size = computed_node.size();
    }
}
```
2024-10-18 22:25:33 +00:00

145 lines
5 KiB
Rust

//! Animates a sprite in response to a keyboard event.
//!
//! See `sprite_sheet.rs` for an example where the sprite animation loops indefinitely.
use std::time::Duration;
use bevy::{input::common_conditions::input_just_pressed, prelude::*};
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) // prevents blurry sprites
.add_systems(Startup, setup)
.add_systems(Update, execute_animations)
.add_systems(
Update,
(
// press the right arrow key to animate the right sprite
trigger_animation::<RightSprite>.run_if(input_just_pressed(KeyCode::ArrowRight)),
// press the left arrow key to animate the left sprite
trigger_animation::<LeftSprite>.run_if(input_just_pressed(KeyCode::ArrowLeft)),
),
)
.run();
}
// This system runs when the user clicks the left arrow key or right arrow key
fn trigger_animation<S: Component>(mut animation: Single<&mut AnimationConfig, With<S>>) {
// we create a new timer when the animation is triggered
animation.frame_timer = AnimationConfig::timer_from_fps(animation.fps);
}
#[derive(Component)]
struct AnimationConfig {
first_sprite_index: usize,
last_sprite_index: usize,
fps: u8,
frame_timer: Timer,
}
impl AnimationConfig {
fn new(first: usize, last: usize, fps: u8) -> Self {
Self {
first_sprite_index: first,
last_sprite_index: last,
fps,
frame_timer: Self::timer_from_fps(fps),
}
}
fn timer_from_fps(fps: u8) -> Timer {
Timer::new(Duration::from_secs_f32(1.0 / (fps as f32)), TimerMode::Once)
}
}
// This system loops through all the sprites in the `TextureAtlas`, from `first_sprite_index` to
// `last_sprite_index` (both defined in `AnimationConfig`).
fn execute_animations(time: Res<Time>, mut query: Query<(&mut AnimationConfig, &mut Sprite)>) {
for (mut config, mut sprite) in &mut query {
// we track how long the current sprite has been displayed for
config.frame_timer.tick(time.delta());
// If it has been displayed for the user-defined amount of time (fps)...
if config.frame_timer.just_finished() {
if let Some(atlas) = &mut sprite.texture_atlas {
if atlas.index == config.last_sprite_index {
// ...and it IS the last frame, then we move back to the first frame and stop.
atlas.index = config.first_sprite_index;
} else {
// ...and it is NOT the last frame, then we move to the next frame...
atlas.index += 1;
// ...and reset the frame timer to start counting all over again
config.frame_timer = AnimationConfig::timer_from_fps(config.fps);
}
}
}
}
}
#[derive(Component)]
struct LeftSprite;
#[derive(Component)]
struct RightSprite;
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
commands.spawn(Camera2d);
// load the sprite sheet using the `AssetServer`
let texture = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png");
// the sprite sheet has 7 sprites arranged in a row, and they are all 24px x 24px
let layout = TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None);
let texture_atlas_layout = texture_atlas_layouts.add(layout);
// the first (left-hand) sprite runs at 10 FPS
let animation_config_1 = AnimationConfig::new(1, 6, 10);
// create the first (left-hand) sprite
commands.spawn((
Sprite {
image: texture.clone(),
texture_atlas: Some(TextureAtlas {
layout: texture_atlas_layout.clone(),
index: animation_config_1.first_sprite_index,
}),
..default()
},
Transform::from_scale(Vec3::splat(6.0)).with_translation(Vec3::new(-50.0, 0.0, 0.0)),
LeftSprite,
animation_config_1,
));
// the second (right-hand) sprite runs at 20 FPS
let animation_config_2 = AnimationConfig::new(1, 6, 20);
// create the second (right-hand) sprite
commands.spawn((
Sprite {
image: texture.clone(),
texture_atlas: Some(TextureAtlas {
layout: texture_atlas_layout.clone(),
index: animation_config_2.first_sprite_index,
}),
..Default::default()
},
Transform::from_scale(Vec3::splat(6.0)).with_translation(Vec3::new(50.0, 0.0, 0.0)),
RightSprite,
animation_config_2,
));
// create a minimal UI explaining how to interact with the example
commands.spawn((
Text::new("Left Arrow Key: Animate Left Sprite\nRight Arrow Key: Animate Right Sprite"),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
}