docs/bevy/examples/transforms/translation.rs 2.1 K · 71 lines · raw · history

1 //! Illustrates how to move an object along an axis.
2
3 use bevy::prelude::*;
4
5 // Define a struct to keep some information about our entity.
6 // Here it's an arbitrary movement speed, the spawn location, and a maximum distance from it.
7 #[derive(Component)]
8 struct Movable {
9 spawn: Vec3,
10 max_distance: f32,
11 speed: f32,
12 }
13
14 // Implement a utility function for easier Movable struct creation.
15 impl Movable {
16 fn new(spawn: Vec3) -> Self {
17 Movable {
18 spawn,
19 max_distance: 5.0,
20 speed: 2.0,
21 }
22 }
23 }
24
25 fn main() {
26 App::new()
27 .add_plugins(DefaultPlugins)
28 .add_systems(Startup, setup)
29 .add_systems(Update, move_cube)
30 .run();
31 }
32
33 // Startup system to setup the scene and spawn all relevant entities.
34 fn setup(
35 mut commands: Commands,
36 mut meshes: ResMut<Assets<Mesh>>,
37 mut materials: ResMut<Assets<StandardMaterial>>,
38 ) {
39 // Add a cube to visualize translation.
40 let entity_spawn = Vec3::ZERO;
41 commands.spawn((
42 Mesh3d(meshes.add(Cuboid::default())),
43 MeshMaterial3d(materials.add(Color::WHITE)),
44 Transform::from_translation(entity_spawn),
45 Movable::new(entity_spawn),
46 ));
47
48 // Spawn a camera looking at the entities to show what's happening in this example.
49 commands.spawn((
50 Camera3d::default(),
51 Transform::from_xyz(0.0, 10.0, 20.0).looking_at(entity_spawn, Vec3::Y),
52 ));
53
54 // Add a light source for better 3d visibility.
55 commands.spawn((
56 DirectionalLight::default(),
57 Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
58 ));
59 }
60
61 // This system will move all Movable entities with a Transform
62 fn move_cube(mut cubes: Query<(&mut Transform, &mut Movable)>, timer: Res<Time>) {
63 for (mut transform, mut cube) in &mut cubes {
64 // Check if the entity moved too far from its spawn, if so invert the moving direction.
65 if (cube.spawn - transform.translation).length() > cube.max_distance {
66 cube.speed *= -1.0;
67 }
68 let direction = transform.local_x();
69 transform.translation += direction * cube.speed * timer.delta_secs();
70 }
71 }