Path: blob/main/examples/animation/gltf_skinned_mesh.rs
6592 views
//! Skinned mesh example with mesh and joints data loaded from a glTF file.1//! Example taken from <https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_019_SimpleSkin.md>23use std::f32::consts::*;45use bevy::{math::ops, mesh::skinning::SkinnedMesh, prelude::*};67fn main() {8App::new()9.add_plugins(DefaultPlugins)10.insert_resource(AmbientLight {11brightness: 750.0,12..default()13})14.add_systems(Startup, setup)15.add_systems(Update, joint_animation)16.run();17}1819fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {20// Create a camera21commands.spawn((22Camera3d::default(),23Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::new(0.0, 1.0, 0.0), Vec3::Y),24));2526// Spawn the first scene in `models/SimpleSkin/SimpleSkin.gltf`27commands.spawn(SceneRoot(asset_server.load(28GltfAssetLabel::Scene(0).from_asset("models/SimpleSkin/SimpleSkin.gltf"),29)));30}3132/// The scene hierarchy currently looks somewhat like this:33///34/// ```text35/// <Parent entity>36/// + Mesh node (without `Mesh3d` or `SkinnedMesh` component)37/// + Skinned mesh entity (with `Mesh3d` and `SkinnedMesh` component, created by glTF loader)38/// + First joint39/// + Second joint40/// ```41///42/// In this example, we want to get and animate the second joint.43/// It is similar to the animation defined in `models/SimpleSkin/SimpleSkin.gltf`.44fn joint_animation(45time: Res<Time>,46children: Query<&ChildOf, With<SkinnedMesh>>,47parents: Query<&Children>,48mut transform_query: Query<&mut Transform>,49) {50// Iter skinned mesh entity51for child_of in &children {52// Mesh node is the parent of the skinned mesh entity.53let mesh_node_entity = child_of.parent();54// Get `Children` in the mesh node.55let mesh_node_parent = parents.get(mesh_node_entity).unwrap();5657// First joint is the second child of the mesh node.58let first_joint_entity = mesh_node_parent[1];59// Get `Children` in the first joint.60let first_joint_children = parents.get(first_joint_entity).unwrap();6162// Second joint is the first child of the first joint.63let second_joint_entity = first_joint_children[0];64// Get `Transform` in the second joint.65let mut second_joint_transform = transform_query.get_mut(second_joint_entity).unwrap();6667second_joint_transform.rotation =68Quat::from_rotation_z(FRAC_PI_2 * ops::sin(time.elapsed_secs()));69}70}717273