move_sprite/
move_sprite.rs

1//! Renders a 2D scene containing a single, moving sprite.
2
3use bevy::prelude::*;
4
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Startup, setup)
9        .add_systems(Update, sprite_movement)
10        .run();
11}
12
13#[derive(Component)]
14enum Direction {
15    Left,
16    Right,
17}
18
19fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
20    commands.spawn(Camera2d);
21
22    commands.spawn((
23        Sprite::from_image(asset_server.load("branding/icon.png")),
24        Transform::from_xyz(0., 0., 0.),
25        Direction::Right,
26    ));
27}
28
29/// The sprite is animated by changing its translation depending on the time that has passed since
30/// the last frame.
31fn sprite_movement(time: Res<Time>, mut sprite_position: Query<(&mut Direction, &mut Transform)>) {
32    for (mut logo, mut transform) in &mut sprite_position {
33        match *logo {
34            Direction::Right => transform.translation.x += 150. * time.delta_secs(),
35            Direction::Left => transform.translation.x -= 150. * time.delta_secs(),
36        }
37
38        if transform.translation.x > 200. {
39            *logo = Direction::Left;
40        } else if transform.translation.x < -200. {
41            *logo = Direction::Right;
42        }
43    }
44}