parenting/
parenting.rs

1//! Illustrates how to create parent-child relationships between entities and how parent transforms
2//! are propagated to their descendants.
3
4use bevy::prelude::*;
5
6fn main() {
7    App::new()
8        .add_plugins(DefaultPlugins)
9        .add_systems(Startup, setup)
10        .add_systems(Update, rotator_system)
11        .run();
12}
13
14/// this component indicates what entities should rotate
15#[derive(Component)]
16struct Rotator;
17
18/// rotates the parent, which will result in the child also rotating
19fn rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<Rotator>>) {
20    for mut transform in &mut query {
21        transform.rotate_x(3.0 * time.delta_secs());
22    }
23}
24
25/// set up a simple scene with a "parent" cube and a "child" cube
26fn setup(
27    mut commands: Commands,
28    mut meshes: ResMut<Assets<Mesh>>,
29    mut materials: ResMut<Assets<StandardMaterial>>,
30) {
31    let cube_handle = meshes.add(Cuboid::new(2.0, 2.0, 2.0));
32    let cube_material_handle = materials.add(StandardMaterial {
33        base_color: Color::srgb(0.8, 0.7, 0.6),
34        ..default()
35    });
36
37    // parent cube
38    commands
39        .spawn((
40            Mesh3d(cube_handle.clone()),
41            MeshMaterial3d(cube_material_handle.clone()),
42            Transform::from_xyz(0.0, 0.0, 1.0),
43            Rotator,
44        ))
45        .with_children(|parent| {
46            // child cube
47            parent.spawn((
48                Mesh3d(cube_handle),
49                MeshMaterial3d(cube_material_handle),
50                Transform::from_xyz(0.0, 0.0, 3.0),
51            ));
52        });
53    // light
54    commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 5.0, -4.0)));
55    // camera
56    commands.spawn((
57        Camera3d::default(),
58        Transform::from_xyz(5.0, 10.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
59    ));
60}