docs/bevy/examples/time/virtual_time.rs 6.2 K · 195 lines · raw · history

1 //! Shows how `Time<Virtual>` can be used to pause, resume, slow down
2 //! and speed up a game.
3
4 use std::time::Duration;
5
6 use bevy::{
7 color::palettes::css::*, input::common_conditions::input_just_pressed, prelude::*,
8 time::common_conditions::on_real_timer,
9 };
10
11 fn main() {
12 App::new()
13 .add_plugins(DefaultPlugins)
14 .add_systems(Startup, setup)
15 .add_systems(
16 Update,
17 (
18 move_virtual_time_sprites,
19 move_real_time_sprites,
20 toggle_pause.run_if(input_just_pressed(KeyCode::Space)),
21 change_time_speed::<1>.run_if(input_just_pressed(KeyCode::ArrowUp)),
22 change_time_speed::<-1>.run_if(input_just_pressed(KeyCode::ArrowDown)),
23 (update_virtual_time_info_text, update_real_time_info_text)
24 // update the texts on a timer to make them more readable.
25 // `on_timer` run condition uses `Virtual` time meaning it's scaled
26 // and would result in the UI updating at different intervals based
27 // on `Time<Virtual>::relative_speed` and `Time<Virtual>::is_paused()`
28 .run_if(on_real_timer(Duration::from_millis(250))),
29 ),
30 )
31 .run();
32 }
33
34 /// `Real` time related marker
35 #[derive(Component)]
36 struct RealTime;
37
38 /// `Virtual` time related marker
39 #[derive(Component)]
40 struct VirtualTime;
41
42 /// Setup the example
43 fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut time: ResMut<Time<Virtual>>) {
44 // start with double `Virtual` time resulting in one of the sprites moving at twice the speed
45 // of the other sprite which moves based on `Real` (unscaled) time
46 time.set_relative_speed(2.);
47
48 commands.spawn(Camera2d);
49
50 let virtual_color = GOLD.into();
51 let sprite_scale = Vec2::splat(0.5).extend(1.);
52 let texture_handle = asset_server.load("branding/icon.png");
53
54 // the sprite moving based on real time
55 commands.spawn((
56 Sprite::from_image(texture_handle.clone()),
57 Transform::from_scale(sprite_scale),
58 RealTime,
59 ));
60
61 // the sprite moving based on virtual time
62 commands.spawn((
63 Sprite {
64 image: texture_handle,
65 color: virtual_color,
66 ..Default::default()
67 },
68 Transform {
69 scale: sprite_scale,
70 translation: Vec3::new(0., -160., 0.),
71 ..default()
72 },
73 VirtualTime,
74 ));
75
76 // info UI
77 let font_size = FontSize::Px(33.);
78
79 commands.spawn((
80 Node {
81 display: Display::Flex,
82 justify_content: JustifyContent::SpaceBetween,
83 width: percent(100),
84 position_type: PositionType::Absolute,
85 top: px(0),
86 padding: UiRect::all(px(20)),
87 ..default()
88 },
89 children![
90 (
91 Text::default(),
92 TextFont {
93 font_size,
94 ..default()
95 },
96 RealTime,
97 ),
98 (
99 Text::new("CONTROLS\n(Un)pause: Space\nSpeed+: Up\nSpeed-: Down"),
100 TextFont {
101 font_size,
102 ..default()
103 },
104 TextColor(Color::srgb(0.85, 0.85, 0.85)),
105 TextLayout::justify(Justify::Center),
106 ),
107 (
108 Text::default(),
109 TextFont {
110 font_size,
111 ..default()
112 },
113 TextColor(virtual_color),
114 TextLayout::justify(Justify::Right),
115 VirtualTime,
116 ),
117 ],
118 ));
119 }
120
121 /// Move sprites using `Real` (unscaled) time
122 fn move_real_time_sprites(
123 mut sprite_query: Query<&mut Transform, (With<Sprite>, With<RealTime>)>,
124 // `Real` time which is not scaled or paused
125 time: Res<Time<Real>>,
126 ) {
127 for mut transform in sprite_query.iter_mut() {
128 // move roughly half the screen in a `Real` second
129 // when the time is scaled the speed is going to change
130 // and the sprite will stay still the time is paused
131 transform.translation.x = get_sprite_translation_x(time.elapsed_secs());
132 }
133 }
134
135 /// Move sprites using `Virtual` (scaled) time
136 fn move_virtual_time_sprites(
137 mut sprite_query: Query<&mut Transform, (With<Sprite>, With<VirtualTime>)>,
138 // the default `Time` is either `Time<Virtual>` in regular systems
139 // or `Time<Fixed>` in fixed timestep systems so `Time::delta()`,
140 // `Time::elapsed()` will return the appropriate values either way
141 time: Res<Time>,
142 ) {
143 for mut transform in sprite_query.iter_mut() {
144 // move roughly half the screen in a `Virtual` second
145 // when time is scaled using `Time<Virtual>::set_relative_speed` it's going
146 // to move at a different pace and the sprite will stay still when time is
147 // `Time<Virtual>::is_paused()`
148 transform.translation.x = get_sprite_translation_x(time.elapsed_secs());
149 }
150 }
151
152 fn get_sprite_translation_x(elapsed: f32) -> f32 {
153 ops::sin(elapsed) * 500.
154 }
155
156 /// Update the speed of `Time<Virtual>.` by `DELTA`
157 fn change_time_speed<const DELTA: i8>(mut time: ResMut<Time<Virtual>>) {
158 let time_speed = (time.relative_speed() + DELTA as f32)
159 .round()
160 .clamp(0.25, 5.);
161
162 // set the speed of the virtual time to speed it up or slow it down
163 time.set_relative_speed(time_speed);
164 }
165
166 /// Pause or resume `Relative` time
167 fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
168 time.toggle();
169 }
170
171 /// Update the `Real` time info text
172 fn update_real_time_info_text(time: Res<Time<Real>>, mut query: Query<&mut Text, With<RealTime>>) {
173 for mut text in &mut query {
174 **text = format!(
175 "REAL TIME\nElapsed: {:.1}\nDelta: {:.5}\n",
176 time.elapsed_secs(),
177 time.delta_secs(),
178 );
179 }
180 }
181
182 /// Update the `Virtual` time info text
183 fn update_virtual_time_info_text(
184 time: Res<Time<Virtual>>,
185 mut query: Query<&mut Text, With<VirtualTime>>,
186 ) {
187 for mut text in &mut query {
188 **text = format!(
189 "VIRTUAL TIME\nElapsed: {:.1}\nDelta: {:.5}\nSpeed: {:.2}",
190 time.elapsed_secs(),
191 time.delta_secs(),
192 time.relative_speed()
193 );
194 }
195 }