Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/3d/parenting.rs
6592 views
1
//! Illustrates how to create parent-child relationships between entities and how parent transforms
2
//! are propagated to their descendants.
3
4
use bevy::prelude::*;
5
6
fn 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)]
16
struct Rotator;
17
18
/// rotates the parent, which will result in the child also rotating
19
fn 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
26
fn 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.spawn((
39
Mesh3d(cube_handle.clone()),
40
MeshMaterial3d(cube_material_handle.clone()),
41
Transform::from_xyz(0.0, 0.0, 1.0),
42
Rotator,
43
children![(
44
// child cube
45
Mesh3d(cube_handle),
46
MeshMaterial3d(cube_material_handle),
47
Transform::from_xyz(0.0, 0.0, 3.0),
48
)],
49
));
50
// light
51
commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 5.0, -4.0)));
52
// camera
53
commands.spawn((
54
Camera3d::default(),
55
Transform::from_xyz(5.0, 10.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
56
));
57
}
58
59