translation/
translation.rs1use bevy::prelude::*;
4
5#[derive(Component)]
8struct Movable {
9 spawn: Vec3,
10 max_distance: f32,
11 speed: f32,
12}
13
14impl Movable {
16 fn new(spawn: Vec3) -> Self {
17 Movable {
18 spawn,
19 max_distance: 5.0,
20 speed: 2.0,
21 }
22 }
23}
24
25fn main() {
26 App::new()
27 .add_plugins(DefaultPlugins)
28 .add_systems(Startup, setup)
29 .add_systems(Update, move_cube)
30 .run();
31}
32
33fn setup(
35 mut commands: Commands,
36 mut meshes: ResMut<Assets<Mesh>>,
37 mut materials: ResMut<Assets<StandardMaterial>>,
38) {
39 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 commands.spawn((
50 Camera3d::default(),
51 Transform::from_xyz(0.0, 10.0, 20.0).looking_at(entity_spawn, Vec3::Y),
52 ));
53
54 commands.spawn((
56 DirectionalLight::default(),
57 Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
58 ));
59}
60
61fn move_cube(mut cubes: Query<(&mut Transform, &mut Movable)>, timer: Res<Time>) {
63 for (mut transform, mut cube) in &mut cubes {
64 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}