Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/animation/animated_ui.rs
9349 views
1
//! Shows how to use animation clips to animate UI properties.
2
3
use bevy::{
4
animation::{
5
animated_field, AnimatedBy, AnimationEntityMut, AnimationEvaluationError, AnimationTargetId,
6
},
7
prelude::*,
8
};
9
10
use std::any::TypeId;
11
12
// Holds information about the animation we programmatically create.
13
struct AnimationInfo {
14
// The name of the animation target (in this case, the text).
15
target_name: Name,
16
// The ID of the animation target, derived from the name.
17
target_id: AnimationTargetId,
18
// The animation graph asset.
19
graph: Handle<AnimationGraph>,
20
// The index of the node within that graph.
21
node_index: AnimationNodeIndex,
22
}
23
24
// The entry point.
25
fn main() {
26
App::new()
27
.add_plugins(DefaultPlugins)
28
// Note that we don't need any systems other than the setup system,
29
// because Bevy automatically updates animations every frame.
30
.add_systems(Startup, setup)
31
.run();
32
}
33
34
impl AnimationInfo {
35
// Programmatically creates the UI animation.
36
fn create(
37
animation_graphs: &mut Assets<AnimationGraph>,
38
animation_clips: &mut Assets<AnimationClip>,
39
) -> AnimationInfo {
40
// Create an ID that identifies the text node we're going to animate.
41
let animation_target_name = Name::new("Text");
42
let animation_target_id = AnimationTargetId::from_name(&animation_target_name);
43
44
// Allocate an animation clip.
45
let mut animation_clip = AnimationClip::default();
46
47
// Create a curve that animates `UiTransform::scale`.
48
animation_clip.add_curve_to_target(
49
animation_target_id,
50
AnimatableCurve::new(
51
animated_field!(UiTransform::scale),
52
AnimatableKeyframeCurve::new(
53
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
54
.into_iter()
55
.zip([0.3, 1.0, 0.3, 1.0, 0.3, 1.0, 0.3].map(Vec2::splat)),
56
)
57
.expect(
58
"should be able to build translation curve because we pass in valid samples",
59
),
60
),
61
);
62
63
// Create a curve that animates font color. Note that this should have
64
// the same time duration as the previous curve.
65
//
66
// This time we use a "custom property", which in this case animates TextColor under the assumption
67
// that it is in the "srgba" format.
68
animation_clip.add_curve_to_target(
69
animation_target_id,
70
AnimatableCurve::new(
71
TextColorProperty,
72
AnimatableKeyframeCurve::new([0.0, 1.0, 2.0, 3.0].into_iter().zip([
73
Srgba::RED,
74
Srgba::GREEN,
75
Srgba::BLUE,
76
Srgba::RED,
77
]))
78
.expect(
79
"should be able to build translation curve because we pass in valid samples",
80
),
81
),
82
);
83
84
// Save our animation clip as an asset.
85
let animation_clip_handle = animation_clips.add(animation_clip);
86
87
// Create an animation graph with that clip.
88
let (animation_graph, animation_node_index) =
89
AnimationGraph::from_clip(animation_clip_handle);
90
let animation_graph_handle = animation_graphs.add(animation_graph);
91
92
AnimationInfo {
93
target_name: animation_target_name,
94
target_id: animation_target_id,
95
graph: animation_graph_handle,
96
node_index: animation_node_index,
97
}
98
}
99
}
100
101
// Creates all the entities in the scene.
102
fn setup(
103
mut commands: Commands,
104
asset_server: Res<AssetServer>,
105
mut animation_graphs: ResMut<Assets<AnimationGraph>>,
106
mut animation_clips: ResMut<Assets<AnimationClip>>,
107
) {
108
// Create the animation.
109
let AnimationInfo {
110
target_name: animation_target_name,
111
target_id: animation_target_id,
112
graph: animation_graph,
113
node_index: animation_node_index,
114
} = AnimationInfo::create(animation_graphs.as_mut(), animation_clips.as_mut());
115
116
// Build an animation player that automatically plays the UI animation.
117
let mut animation_player = AnimationPlayer::default();
118
animation_player.play(animation_node_index).repeat();
119
120
// Add a camera.
121
commands.spawn(Camera2d);
122
123
// Build the UI. We have a parent node that covers the whole screen and
124
// contains the `AnimationPlayer`, as well as a child node that contains the
125
// text to be animated.
126
let mut entity = commands.spawn((
127
// Cover the whole screen, and center contents.
128
Node {
129
position_type: PositionType::Absolute,
130
top: px(0),
131
left: px(0),
132
right: px(0),
133
bottom: px(0),
134
justify_content: JustifyContent::Center,
135
align_items: AlignItems::Center,
136
..default()
137
},
138
animation_player,
139
AnimationGraphHandle(animation_graph),
140
));
141
142
let player = entity.id();
143
entity.with_child((
144
Text::new("Bevy"),
145
TextFont {
146
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
147
font_size: FontSize::Px(80.),
148
..default()
149
},
150
TextColor(Color::Srgba(Srgba::RED)),
151
TextLayout::new_with_justify(Justify::Center),
152
animation_target_id,
153
AnimatedBy(player),
154
animation_target_name,
155
));
156
}
157
158
// A type that represents the color of the first text section.
159
//
160
// We implement `AnimatableProperty` on this to define custom property accessor logic
161
#[derive(Clone)]
162
struct TextColorProperty;
163
164
impl AnimatableProperty for TextColorProperty {
165
type Property = Srgba;
166
167
fn evaluator_id(&self) -> EvaluatorId<'_> {
168
EvaluatorId::Type(TypeId::of::<Self>())
169
}
170
171
fn get_mut<'a>(
172
&self,
173
entity: &'a mut AnimationEntityMut,
174
) -> Result<&'a mut Self::Property, AnimationEvaluationError> {
175
let text_color = entity
176
.get_mut::<TextColor>()
177
.ok_or(AnimationEvaluationError::ComponentNotPresent(TypeId::of::<
178
TextColor,
179
>(
180
)))?
181
.into_inner();
182
match text_color.0 {
183
Color::Srgba(ref mut color) => Ok(color),
184
_ => Err(AnimationEvaluationError::PropertyNotPresent(TypeId::of::<
185
Srgba,
186
>(
187
))),
188
}
189
}
190
}
191
192