Path: blob/main/examples/animation/animated_mesh_events.rs
6592 views
//! Plays animations from a skinned glTF.12use std::{f32::consts::PI, time::Duration};34use bevy::{5animation::AnimationTargetId, color::palettes::css::WHITE, light::CascadeShadowConfigBuilder,6prelude::*,7};8use rand::{Rng, SeedableRng};9use rand_chacha::ChaCha8Rng;1011const FOX_PATH: &str = "models/animated/Fox.glb";1213fn main() {14App::new()15.insert_resource(AmbientLight {16color: Color::WHITE,17brightness: 2000.,18..default()19})20.add_plugins(DefaultPlugins)21.init_resource::<ParticleAssets>()22.init_resource::<FoxFeetTargets>()23.add_systems(Startup, setup)24.add_systems(Update, setup_scene_once_loaded)25.add_systems(Update, simulate_particles)26.add_observer(observe_on_step)27.run();28}2930#[derive(Resource)]31struct SeededRng(ChaCha8Rng);3233#[derive(Resource)]34struct Animations {35index: AnimationNodeIndex,36graph_handle: Handle<AnimationGraph>,37}3839#[derive(EntityEvent, Reflect, Clone)]40struct OnStep;4142fn observe_on_step(43event: On<OnStep>,44particle: Res<ParticleAssets>,45mut commands: Commands,46transforms: Query<&GlobalTransform>,47mut seeded_rng: ResMut<SeededRng>,48) {49let translation = transforms.get(event.entity()).unwrap().translation();50// Spawn a bunch of particles.51for _ in 0..14 {52let horizontal = seeded_rng.0.random::<Dir2>() * seeded_rng.0.random_range(8.0..12.0);53let vertical = seeded_rng.0.random_range(0.0..4.0);54let size = seeded_rng.0.random_range(0.2..1.0);5556commands.spawn((57Particle {58lifetime_timer: Timer::from_seconds(59seeded_rng.0.random_range(0.2..0.6),60TimerMode::Once,61),62size,63velocity: Vec3::new(horizontal.x, vertical, horizontal.y) * 10.0,64},65Mesh3d(particle.mesh.clone()),66MeshMaterial3d(particle.material.clone()),67Transform {68translation,69scale: Vec3::splat(size),70..Default::default()71},72));73}74}7576fn setup(77mut commands: Commands,78asset_server: Res<AssetServer>,79mut meshes: ResMut<Assets<Mesh>>,80mut materials: ResMut<Assets<StandardMaterial>>,81mut graphs: ResMut<Assets<AnimationGraph>>,82) {83// Build the animation graph84let (graph, index) = AnimationGraph::from_clip(85// We specifically want the "run" animation, which is the third one.86asset_server.load(GltfAssetLabel::Animation(2).from_asset(FOX_PATH)),87);8889// Insert a resource with the current scene information90let graph_handle = graphs.add(graph);91commands.insert_resource(Animations {92index,93graph_handle,94});9596// Camera97commands.spawn((98Camera3d::default(),99Transform::from_xyz(100.0, 100.0, 150.0).looking_at(Vec3::new(0.0, 20.0, 0.0), Vec3::Y),100));101102// Plane103commands.spawn((104Mesh3d(meshes.add(Plane3d::default().mesh().size(500000.0, 500000.0))),105MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),106));107108// Light109commands.spawn((110Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),111DirectionalLight {112shadows_enabled: true,113..default()114},115CascadeShadowConfigBuilder {116first_cascade_far_bound: 200.0,117maximum_distance: 400.0,118..default()119}120.build(),121));122123// Fox124commands.spawn(SceneRoot(125asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_PATH)),126));127128// We're seeding the PRNG here to make this example deterministic for testing purposes.129// This isn't strictly required in practical use unless you need your app to be deterministic.130let seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712);131commands.insert_resource(SeededRng(seeded_rng));132}133134// An `AnimationPlayer` is automatically added to the scene when it's ready.135// When the player is added, start the animation.136fn setup_scene_once_loaded(137mut commands: Commands,138animations: Res<Animations>,139feet: Res<FoxFeetTargets>,140graphs: Res<Assets<AnimationGraph>>,141mut clips: ResMut<Assets<AnimationClip>>,142mut players: Query<(Entity, &mut AnimationPlayer), Added<AnimationPlayer>>,143) {144fn get_clip<'a>(145node: AnimationNodeIndex,146graph: &AnimationGraph,147clips: &'a mut Assets<AnimationClip>,148) -> &'a mut AnimationClip {149let node = graph.get(node).unwrap();150let clip = match &node.node_type {151AnimationNodeType::Clip(handle) => clips.get_mut(handle),152_ => unreachable!(),153};154clip.unwrap()155}156157for (entity, mut player) in &mut players {158// Send `OnStep` events once the fox feet hits the ground in the running animation.159160let graph = graphs.get(&animations.graph_handle).unwrap();161let running_animation = get_clip(animations.index, graph, &mut clips);162163// You can determine the time an event should trigger if you know witch frame it occurs and164// the frame rate of the animation. Let's say we want to trigger an event at frame 15,165// and the animation has a frame rate of 24 fps, then time = 15 / 24 = 0.625.166running_animation.add_event_to_target(feet.front_left, 0.625, OnStep);167running_animation.add_event_to_target(feet.front_right, 0.5, OnStep);168running_animation.add_event_to_target(feet.back_left, 0.0, OnStep);169running_animation.add_event_to_target(feet.back_right, 0.125, OnStep);170171// Start the animation172173let mut transitions = AnimationTransitions::new();174175// Make sure to start the animation via the `AnimationTransitions`176// component. The `AnimationTransitions` component wants to manage all177// the animations and will get confused if the animations are started178// directly via the `AnimationPlayer`.179transitions180.play(&mut player, animations.index, Duration::ZERO)181.repeat();182183commands184.entity(entity)185.insert(AnimationGraphHandle(animations.graph_handle.clone()))186.insert(transitions);187}188}189190fn simulate_particles(191mut commands: Commands,192mut query: Query<(Entity, &mut Transform, &mut Particle)>,193time: Res<Time>,194) {195for (entity, mut transform, mut particle) in &mut query {196if particle.lifetime_timer.tick(time.delta()).just_finished() {197commands.entity(entity).despawn();198return;199}200201transform.translation += particle.velocity * time.delta_secs();202transform.scale = Vec3::splat(particle.size.lerp(0.0, particle.lifetime_timer.fraction()));203particle204.velocity205.smooth_nudge(&Vec3::ZERO, 4.0, time.delta_secs());206}207}208209#[derive(Component)]210struct Particle {211lifetime_timer: Timer,212size: f32,213velocity: Vec3,214}215216#[derive(Resource)]217struct ParticleAssets {218mesh: Handle<Mesh>,219material: Handle<StandardMaterial>,220}221222impl FromWorld for ParticleAssets {223fn from_world(world: &mut World) -> Self {224Self {225mesh: world.add_asset::<Mesh>(Sphere::new(10.0)),226material: world.add_asset::<StandardMaterial>(StandardMaterial {227base_color: WHITE.into(),228..Default::default()229}),230}231}232}233234/// Stores the `AnimationTargetId`s of the fox's feet235#[derive(Resource)]236struct FoxFeetTargets {237front_right: AnimationTargetId,238front_left: AnimationTargetId,239back_left: AnimationTargetId,240back_right: AnimationTargetId,241}242243impl Default for FoxFeetTargets {244fn default() -> Self {245let hip_node = ["root", "_rootJoint", "b_Root_00", "b_Hip_01"];246let front_left_foot = hip_node.iter().chain(247[248"b_Spine01_02",249"b_Spine02_03",250"b_LeftUpperArm_09",251"b_LeftForeArm_010",252"b_LeftHand_011",253]254.iter(),255);256let front_right_foot = hip_node.iter().chain(257[258"b_Spine01_02",259"b_Spine02_03",260"b_RightUpperArm_06",261"b_RightForeArm_07",262"b_RightHand_08",263]264.iter(),265);266let back_left_foot = hip_node.iter().chain(267[268"b_LeftLeg01_015",269"b_LeftLeg02_016",270"b_LeftFoot01_017",271"b_LeftFoot02_018",272]273.iter(),274);275let back_right_foot = hip_node.iter().chain(276[277"b_RightLeg01_019",278"b_RightLeg02_020",279"b_RightFoot01_021",280"b_RightFoot02_022",281]282.iter(),283);284Self {285front_left: AnimationTargetId::from_iter(front_left_foot),286front_right: AnimationTargetId::from_iter(front_right_foot),287back_left: AnimationTargetId::from_iter(back_left_foot),288back_right: AnimationTargetId::from_iter(back_right_foot),289}290}291}292293294