Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/animation/animation_events.rs
6592 views
1
//! Demonstrate how to use animation events.
2
3
use bevy::{
4
color::palettes::css::{ALICE_BLUE, BLACK, CRIMSON},
5
post_process::bloom::Bloom,
6
prelude::*,
7
};
8
9
fn main() {
10
App::new()
11
.add_plugins(DefaultPlugins)
12
.add_systems(Startup, setup)
13
.add_systems(Update, animate_text_opacity)
14
.add_observer(edit_message)
15
.run();
16
}
17
18
#[derive(Component)]
19
struct MessageText;
20
21
#[derive(EntityEvent, Clone)]
22
struct MessageEvent {
23
value: String,
24
color: Color,
25
}
26
27
fn edit_message(
28
event: On<MessageEvent>,
29
text: Single<(&mut Text2d, &mut TextColor), With<MessageText>>,
30
) {
31
let (mut text, mut color) = text.into_inner();
32
text.0 = event.value.clone();
33
color.0 = event.color;
34
}
35
36
fn setup(
37
mut commands: Commands,
38
mut animations: ResMut<Assets<AnimationClip>>,
39
mut graphs: ResMut<Assets<AnimationGraph>>,
40
) {
41
// Camera
42
commands.spawn((
43
Camera2d,
44
Camera {
45
clear_color: ClearColorConfig::Custom(BLACK.into()),
46
..Default::default()
47
},
48
Bloom {
49
intensity: 0.4,
50
..Bloom::NATURAL
51
},
52
));
53
54
// The text that will be changed by animation events.
55
commands.spawn((
56
MessageText,
57
Text2d::default(),
58
TextFont {
59
font_size: 119.0,
60
..default()
61
},
62
TextColor(Color::NONE),
63
));
64
65
// Create a new animation clip.
66
let mut animation = AnimationClip::default();
67
68
// This is only necessary if you want the duration of the
69
// animation to be longer than the last event in the clip.
70
animation.set_duration(2.0);
71
72
// Add events at the specified time.
73
animation.add_event(
74
0.0,
75
MessageEvent {
76
value: "HELLO".into(),
77
color: ALICE_BLUE.into(),
78
},
79
);
80
animation.add_event(
81
1.0,
82
MessageEvent {
83
value: "BYE".into(),
84
color: CRIMSON.into(),
85
},
86
);
87
88
// Create the animation graph.
89
let (graph, animation_index) = AnimationGraph::from_clip(animations.add(animation));
90
let mut player = AnimationPlayer::default();
91
player.play(animation_index).repeat();
92
93
commands.spawn((AnimationGraphHandle(graphs.add(graph)), player));
94
}
95
96
// Slowly fade out the text opacity.
97
fn animate_text_opacity(mut colors: Query<&mut TextColor>, time: Res<Time>) {
98
for mut color in &mut colors {
99
let a = color.0.alpha();
100
color.0.set_alpha(a - time.delta_secs());
101
}
102
}
103
104