update_gltf_scene/
update_gltf_scene.rs

1//! Update a scene from a glTF file, either by spawning the scene as a child of another entity,
2//! or by accessing the entities of the scene.
3
4use bevy::{light::DirectionalLightShadowMap, prelude::*};
5
6fn main() {
7    App::new()
8        .insert_resource(DirectionalLightShadowMap { size: 4096 })
9        .add_plugins(DefaultPlugins)
10        .add_systems(Startup, setup)
11        .add_systems(Update, move_scene_entities)
12        .run();
13}
14
15#[derive(Component)]
16struct MovedScene;
17
18fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
19    commands.spawn((
20        Transform::from_xyz(4.0, 25.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
21        DirectionalLight {
22            shadows_enabled: true,
23            ..default()
24        },
25    ));
26    commands.spawn((
27        Camera3d::default(),
28        Transform::from_xyz(-0.5, 0.9, 1.5).looking_at(Vec3::new(-0.5, 0.3, 0.0), Vec3::Y),
29        EnvironmentMapLight {
30            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
31            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
32            intensity: 150.0,
33            ..default()
34        },
35    ));
36
37    // Spawn the scene as a child of this entity at the given transform
38    commands.spawn((
39        Transform::from_xyz(-1.0, 0.0, 0.0),
40        SceneRoot(
41            asset_server
42                .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")),
43        ),
44    ));
45
46    // Spawn a second scene, and add a tag component to be able to target it later
47    commands.spawn((
48        SceneRoot(
49            asset_server
50                .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")),
51        ),
52        MovedScene,
53    ));
54}
55
56// This system will move all entities that are descendants of MovedScene (which will be all entities spawned in the scene)
57fn move_scene_entities(
58    time: Res<Time>,
59    moved_scene: Query<Entity, With<MovedScene>>,
60    children: Query<&Children>,
61    mut transforms: Query<&mut Transform>,
62) {
63    for moved_scene_entity in &moved_scene {
64        let mut offset = 0.;
65        for entity in children.iter_descendants(moved_scene_entity) {
66            if let Ok(mut transform) = transforms.get_mut(entity) {
67                transform.translation = Vec3::new(
68                    offset * ops::sin(time.elapsed_secs()) / 20.,
69                    0.,
70                    ops::cos(time.elapsed_secs()) / 20.,
71                );
72                offset += 0.5;
73            }
74        }
75    }
76}