Struct bevy::prelude::Time

pub struct Time<T = ()>
where T: Default,
{ /* private fields */ }
Expand description

A generic clock resource that tracks how much it has advanced since its previous update and since its creation.

Multiple instances of this resource are inserted automatically by TimePlugin:

  • Time<Real> tracks real wall-clock time elapsed.
  • Time<Virtual> tracks virtual game time that may be paused or scaled.
  • Time<Fixed> tracks fixed timesteps based on virtual time.
  • Time is a generic clock that corresponds to “current” or “default” time for systems. It contains Time<Virtual> except inside the FixedMain schedule when it contains Time<Fixed>.

The time elapsed since the previous time this clock was advanced is saved as delta() and the total amount of time the clock has advanced is saved as elapsed(). Both are represented as exact Duration values with fixed nanosecond precision. The clock does not support time moving backwards, but it can be updated with Duration::ZERO which will set delta() to zero.

These values are also available in seconds as f32 via delta_seconds() and elapsed_seconds(), and also in seconds as f64 via delta_seconds_f64() and elapsed_seconds_f64().

Since elapsed_seconds() will grow constantly and is f32, it will exhibit gradual precision loss. For applications that require an f32 value but suffer from gradual precision loss there is elapsed_seconds_wrapped() available. The same wrapped value is also available as Duration and f64 for consistency. The wrap period is by default 1 hour, and can be set by set_wrap_period().

§Accessing clocks

By default, any systems requiring current delta() or elapsed() should use Res<Time> to access the default time configured for the program. By default, this refers to Time<Virtual> except during the FixedMain schedule when it refers to Time<Fixed>. This ensures your system can be used either in Update or FixedUpdate schedule depending on what is needed.

fn ambivalent_system(time: Res<Time>) {
    println!("this how I see time: delta {:?}, elapsed {:?}", time.delta(), time.elapsed());
}

If your system needs to react based on real time (wall clock time), like for user interfaces, it should use Res<Time<Real>>. The delta() and elapsed() values will always correspond to real time and will not be affected by pause, time scaling or other tweaks.

fn real_time_system(time: Res<Time<Real>>) {
    println!("this will always be real time: delta {:?}, elapsed {:?}", time.delta(), time.elapsed());
}

If your system specifically needs to access fixed timestep clock, even when placed in Update schedule, you should use Res<Time<Fixed>>. The delta() and elapsed() values will correspond to the latest fixed timestep that has been run.

fn fixed_time_system(time: Res<Time<Fixed>>) {
    println!("this will always be the last executed fixed timestep: delta {:?}, elapsed {:?}", time.delta(), time.elapsed());
}

Finally, if your system specifically needs to know the current virtual game time, even if placed inside FixedUpdate, for example to know if the game is was_paused() or to use effective_speed(), you can use Res<Time<Virtual>>. However, if the system is placed in FixedUpdate, extra care must be used because your system might be run multiple times with the same delta() and elapsed() values as the virtual game time has not changed between the iterations.

fn fixed_time_system(time: Res<Time<Virtual>>) {
    println!("this will be virtual time for this update: delta {:?}, elapsed {:?}", time.delta(), time.elapsed());
    println!("also the relative speed of the game is now {}", time.effective_speed());
}

If you need to change the settings for any of the clocks, for example to pause() the game, you should use ResMut<Time<Virtual>>.

#[derive(Event)]
struct PauseEvent(bool);

fn pause_system(mut time: ResMut<Time<Virtual>>, mut events: EventReader<PauseEvent>) {
    for ev in events.read() {
        if ev.0 {
            time.pause();
        } else {
            time.unpause();
        }
    }
}

§Adding custom clocks

New custom clocks can be created by creating your own struct as a context and passing it to new_with(). These clocks can be inserted as resources as normal and then accessed by systems. You can use the advance_by() or advance_to() methods to move the clock forwards based on your own logic.

If you want to add methods for your time instance and they require access to both your context and the generic time part, it’s probably simplest to add a custom trait for them and implement it for Time<Custom>.

Your context struct will need to implement the Default trait because Time structures support reflection. It also makes initialization trivial by being able to call app.init_resource::<Time<Custom>>().

You can also replace the “generic” Time clock resource if the “default” time for your game should not be the default virtual time provided. You can get a “generic” snapshot of your clock by calling as_generic() and then overwrite the Time resource with it. The default systems added by TimePlugin will overwrite the Time clock during First and FixedUpdate schedules.

#[derive(Debug)]
struct Custom {
    last_external_time: Instant,
}

impl Default for Custom {
    fn default() -> Self {
        Self {
            last_external_time: Instant::now(),
        }
    }
}

trait CustomTime {
    fn update_from_external(&mut self, instant: Instant);
}

impl CustomTime for Time<Custom> {
    fn update_from_external(&mut self, instant: Instant) {
         let delta = instant - self.context().last_external_time;
         self.advance_by(delta);
         self.context_mut().last_external_time = instant;
    }
}

Implementations§

§

impl Time<Fixed>

pub fn from_duration(timestep: Duration) -> Time<Fixed>

Return new fixed time clock with given timestep as Duration

§Panics

Panics if timestep is zero.

Examples found in repository?
examples/time/time.rs (line 111)
107
108
109
110
111
112
113
114
115
116
117
fn main() {
    App::new()
        .add_plugins(MinimalPlugins)
        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
        .add_systems(PreUpdate, print_real_time)
        .add_systems(FixedUpdate, print_fixed_time)
        .add_systems(Update, print_time)
        .set_runner(runner)
        .run();
}
More examples
Hide additional examples
examples/stress_tests/bevymark.rs (lines 141-143)
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
fn main() {
    // `from_env` panics on the web
    #[cfg(not(target_arch = "wasm32"))]
    let args: Args = argh::from_env();
    #[cfg(target_arch = "wasm32")]
    let args = Args::from_args(&[], &[]).unwrap();

    App::new()
        .add_plugins((
            DefaultPlugins.set(WindowPlugin {
                primary_window: Some(Window {
                    title: "BevyMark".into(),
                    resolution: WindowResolution::new(1920.0, 1080.0)
                        .with_scale_factor_override(1.0),
                    present_mode: PresentMode::AutoNoVsync,
                    ..default()
                }),
                ..default()
            }),
            FrameTimeDiagnosticsPlugin,
            LogDiagnosticsPlugin::default(),
        ))
        .insert_resource(WinitSettings {
            focused_mode: UpdateMode::Continuous,
            unfocused_mode: UpdateMode::Continuous,
        })
        .insert_resource(args)
        .insert_resource(BevyCounter {
            count: 0,
            color: Color::WHITE,
        })
        .add_systems(Startup, setup)
        .add_systems(FixedUpdate, scheduled_spawner)
        .add_systems(
            Update,
            (
                mouse_handler,
                movement_system,
                collision_system,
                counter_system,
            ),
        )
        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs_f32(
            FIXED_TIMESTEP,
        )))
        .run();
}

pub fn from_seconds(seconds: f64) -> Time<Fixed>

Return new fixed time clock with given timestep seconds as f64

§Panics

Panics if seconds is zero, negative or not finite.

Examples found in repository?
examples/ecs/fixed_timestep.rs (line 13)
5
6
7
8
9
10
11
12
13
14
15
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        // this system will run once every update (it should match your screen's refresh rate)
        .add_systems(Update, frame_update)
        // add our system to the fixed timestep schedule
        .add_systems(FixedUpdate, fixed_update)
        // configure our fixed timestep schedule to run twice a second
        .insert_resource(Time::<Fixed>::from_seconds(0.5))
        .run();
}

pub fn from_hz(hz: f64) -> Time<Fixed>

Return new fixed time clock with given timestep frequency in Hertz (1/seconds)

§Panics

Panics if hz is zero, negative or not finite.

Examples found in repository?
examples/2d/rotation.rs (line 10)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .insert_resource(Time::<Fixed>::from_hz(60.0))
        .add_systems(Startup, setup)
        .add_systems(
            FixedUpdate,
            (
                player_movement_system,
                snap_to_player_system,
                rotate_to_player_system,
            ),
        )
        .run();
}

pub fn timestep(&self) -> Duration

Returns the amount of virtual time that must pass before the fixed timestep schedule is run again.

Examples found in repository?
examples/ecs/iter_combinations.rs (line 87)
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
fn generate_bodies(
    time: Res<Time<Fixed>>,
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    let mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap());

    let color_range = 0.5..1.0;
    let vel_range = -0.5..0.5;

    // We're seeding the PRNG here to make this example deterministic for testing purposes.
    // This isn't strictly required in practical use unless you need your app to be deterministic.
    let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
    for _ in 0..NUM_BODIES {
        let radius: f32 = rng.gen_range(0.1..0.7);
        let mass_value = radius.powi(3) * 10.;

        let position = Vec3::new(
            rng.gen_range(-1.0..1.0),
            rng.gen_range(-1.0..1.0),
            rng.gen_range(-1.0..1.0),
        )
        .normalize()
            * rng.gen_range(0.2f32..1.0).cbrt()
            * 15.;

        commands.spawn(BodyBundle {
            pbr: PbrBundle {
                transform: Transform {
                    translation: position,
                    scale: Vec3::splat(radius),
                    ..default()
                },
                mesh: mesh.clone(),
                material: materials.add(Color::srgb(
                    rng.gen_range(color_range.clone()),
                    rng.gen_range(color_range.clone()),
                    rng.gen_range(color_range.clone()),
                )),
                ..default()
            },
            mass: Mass(mass_value),
            acceleration: Acceleration(Vec3::ZERO),
            last_pos: LastPos(
                position
                    - Vec3::new(
                        rng.gen_range(vel_range.clone()),
                        rng.gen_range(vel_range.clone()),
                        rng.gen_range(vel_range.clone()),
                    ) * time.timestep().as_secs_f32(),
            ),
        });
    }

    // add bigger "star" body in the center
    let star_radius = 1.;
    commands
        .spawn((
            BodyBundle {
                pbr: PbrBundle {
                    transform: Transform::from_scale(Vec3::splat(star_radius)),
                    mesh: meshes.add(Sphere::new(1.0).mesh().ico(5).unwrap()),
                    material: materials.add(StandardMaterial {
                        base_color: ORANGE_RED.into(),
                        emissive: (LinearRgba::from(ORANGE_RED) * 18.).into(),
                        ..default()
                    }),
                    ..default()
                },
                mass: Mass(500.0),
                ..default()
            },
            Star,
        ))
        .with_children(|p| {
            p.spawn(PointLightBundle {
                point_light: PointLight {
                    color: Color::WHITE,
                    range: 100.0,
                    radius: star_radius,
                    ..default()
                },
                ..default()
            });
        });
    commands.spawn(Camera3dBundle {
        transform: Transform::from_xyz(0.0, 10.5, -30.0).looking_at(Vec3::ZERO, Vec3::Y),
        ..default()
    });
}

pub fn set_timestep(&mut self, timestep: Duration)

Sets the amount of virtual time that must pass before the fixed timestep schedule is run again, as Duration.

Takes effect immediately on the next run of the schedule, respecting what is currently in Self::overstep.

§Panics

Panics if timestep is zero.

pub fn set_timestep_seconds(&mut self, seconds: f64)

Sets the amount of virtual time that must pass before the fixed timestep schedule is run again, as seconds.

Timestep is stored as a Duration, which has fixed nanosecond resolution and will be converted from the floating point number.

Takes effect immediately on the next run of the schedule, respecting what is currently in Self::overstep.

§Panics

Panics if seconds is zero, negative or not finite.

pub fn set_timestep_hz(&mut self, hz: f64)

Sets the amount of virtual time that must pass before the fixed timestep schedule is run again, as frequency.

The timestep value is set to 1 / hz, converted to a Duration which has fixed nanosecond resolution.

Takes effect immediately on the next run of the schedule, respecting what is currently in Self::overstep.

§Panics

Panics if hz is zero, negative or not finite.

pub fn overstep(&self) -> Duration

Returns the amount of overstep time accumulated toward new steps, as Duration.

Examples found in repository?
examples/ecs/fixed_timestep.rs (line 37)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
fn fixed_update(mut last_time: Local<f32>, time: Res<Time>, fixed_time: Res<Time<Fixed>>) {
    // Default `Time`is `Time<Fixed>` here
    info!(
        "time since last fixed_update: {}\n",
        time.elapsed_seconds() - *last_time
    );

    info!("fixed timestep: {}\n", time.delta_seconds());
    // If we want to see the overstep, we need to access `Time<Fixed>` specifically
    info!(
        "time accrued toward next fixed_update: {}\n",
        fixed_time.overstep().as_secs_f32()
    );
    *last_time = time.elapsed_seconds();
}

pub fn discard_overstep(&mut self, discard: Duration)

Discard a part of the overstep amount.

If discard is higher than overstep, the overstep becomes zero.

pub fn overstep_fraction(&self) -> f32

Returns the amount of overstep time accumulated toward new steps, as an f32 fraction of the timestep.

pub fn overstep_fraction_f64(&self) -> f64

Returns the amount of overstep time accumulated toward new steps, as an f64 fraction of the timestep.

§

impl Time<Real>

pub fn new(startup: Instant) -> Time<Real>

Constructs a new Time<Real> instance with a specific startup Instant.

pub fn update(&mut self)

Updates the internal time measurements.

Calling this method as part of your app will most likely result in inaccurate timekeeping, as the Time resource is ordinarily managed by the TimePlugin.

pub fn update_with_duration(&mut self, duration: Duration)

Updates time with a specified Duration.

This method is provided for use in tests.

Calling this method as part of your app will most likely result in inaccurate timekeeping, as the Time resource is ordinarily managed by the TimePlugin.

pub fn update_with_instant(&mut self, instant: Instant)

Updates time with a specified Instant.

This method is provided for use in tests.

Calling this method as part of your app will most likely result in inaccurate timekeeping, as the Time resource is ordinarily managed by the TimePlugin.

pub fn startup(&self) -> Instant

Returns the Instant the clock was created.

This usually represents when the app was started.

pub fn first_update(&self) -> Option<Instant>

Returns the Instant when Self::update was first called, if it exists.

This usually represents when the first app update started.

pub fn last_update(&self) -> Option<Instant>

Returns the Instant when Self::update was last called, if it exists.

This usually represents when the current app update started.

§

impl<T> Time<T>
where T: Default,

pub fn new_with(context: T) -> Time<T>

Create a new clock from context with Self::delta and Self::elapsed starting from zero.

pub fn advance_by(&mut self, delta: Duration)

Advance this clock by adding a delta duration to it.

The added duration will be returned by Self::delta and Self::elapsed will be increased by the duration. Adding Duration::ZERO is allowed and will set Self::delta to zero.

pub fn advance_to(&mut self, elapsed: Duration)

Advance this clock to a specific elapsed time.

Self::delta() will return the amount of time the clock was advanced and Self::elapsed() will be the elapsed value passed in. Cannot be used to move time backwards.

§Panics

Panics if elapsed is less than Self::elapsed().

pub fn wrap_period(&self) -> Duration

Returns the modulus used to calculate elapsed_wrapped.

Note: The default modulus is one hour.

pub fn set_wrap_period(&mut self, wrap_period: Duration)

Sets the modulus used to calculate elapsed_wrapped.

Note: This will not take effect until the next update.

§Panics

Panics if wrap_period is a zero-length duration.

pub fn delta(&self) -> Duration

Returns how much time has advanced since the last update, as a Duration.

Examples found in repository?
examples/app/plugin.rs (line 48)
47
48
49
50
51
fn print_message_system(mut state: ResMut<PrintMessageState>, time: Res<Time>) {
    if state.timer.tick(time.delta()).finished() {
        info!("{}", state.message);
    }
}
More examples
Hide additional examples
examples/time/time.rs (line 86)
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
fn print_real_time(time: Res<Time<Real>>) {
    println!(
        "PreUpdate: this is real time clock, delta is {:?} and elapsed is {:?}",
        time.delta(),
        time.elapsed()
    );
}

fn print_fixed_time(time: Res<Time>) {
    println!(
        "FixedUpdate: this is generic time clock inside fixed, delta is {:?} and elapsed is {:?}",
        time.delta(),
        time.elapsed()
    );
}

fn print_time(time: Res<Time>) {
    println!(
        "Update: this is generic time clock, delta is {:?} and elapsed is {:?}",
        time.delta(),
        time.elapsed()
    );
}
examples/stress_tests/many_sprites.rs (line 126)
125
126
127
128
129
130
131
fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) {
    timer.tick(time.delta());

    if timer.just_finished() {
        info!("Sprites: {}", sprites.iter().count());
    }
}
examples/stress_tests/many_lights.rs (line 149)
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
fn print_light_count(time: Res<Time>, mut timer: Local<PrintingTimer>, lights: Query<&PointLight>) {
    timer.0.tick(time.delta());

    if timer.0.just_finished() {
        info!("Lights: {}", lights.iter().len());
    }
}

struct LogVisibleLights;

impl Plugin for LogVisibleLights {
    fn build(&self, app: &mut App) {
        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
            return;
        };

        render_app.add_systems(Render, print_visible_light_count.in_set(RenderSet::Prepare));
    }
}

// System for printing the number of meshes on every tick of the timer
fn print_visible_light_count(
    time: Res<Time>,
    mut timer: Local<PrintingTimer>,
    visible: Query<&ExtractedPointLight>,
    global_light_meta: Res<GlobalLightMeta>,
) {
    timer.0.tick(time.delta());

    if timer.0.just_finished() {
        info!(
            "Visible Lights: {}, Rendered Lights: {}",
            visible.iter().len(),
            global_light_meta.entity_to_index.len()
        );
    }
}
examples/ecs/generic_system.rs (line 68)
66
67
68
69
70
71
72
fn print_text_system(time: Res<Time>, mut query: Query<(&mut PrinterTick, &TextToPrint)>) {
    for (mut timer, text) in &mut query {
        if timer.tick(time.delta()).just_finished() {
            info!("{}", text.0);
        }
    }
}
examples/time/timers.rs (line 50)
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
fn print_when_completed(time: Res<Time>, mut query: Query<&mut PrintOnCompletionTimer>) {
    for mut timer in &mut query {
        if timer.tick(time.delta()).just_finished() {
            info!("Entity timer just finished");
        }
    }
}

/// This system controls ticking the timer within the countdown resource and
/// handling its state.
fn countdown(time: Res<Time>, mut countdown: ResMut<Countdown>) {
    countdown.main_timer.tick(time.delta());

    // The API encourages this kind of timer state checking (if you're only checking for one value)
    // Additionally, `finished()` would accomplish the same thing as `just_finished` due to the
    // timer being repeating, however this makes more sense visually.
    if countdown.percent_trigger.tick(time.delta()).just_finished() {
        if !countdown.main_timer.finished() {
            // Print the percent complete the main timer is.
            info!(
                "Timer is {:0.0}% complete!",
                countdown.main_timer.fraction() * 100.0
            );
        } else {
            // The timer has finished so we pause the percent output timer
            countdown.percent_trigger.pause();
            info!("Paused percent trigger timer");
        }
    }
}

pub fn delta_seconds(&self) -> f32

Returns how much time has advanced since the last update, as f32 seconds.

Examples found in repository?
examples/shader/extended_material.rs (line 68)
66
67
68
69
70
fn rotate_things(mut q: Query<&mut Transform, With<Rotate>>, time: Res<Time>) {
    for mut t in &mut q {
        t.rotate_y(time.delta_seconds());
    }
}
More examples
Hide additional examples
examples/3d/3d_shapes.rs (line 95)
93
94
95
96
97
fn rotate(mut query: Query<&mut Transform, With<Shape>>, time: Res<Time>) {
    for mut transform in &mut query {
        transform.rotate_y(time.delta_seconds() / 2.);
    }
}
examples/3d/parenting.rs (line 21)
19
20
21
22
23
fn rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<Rotator>>) {
    for mut transform in &mut query {
        transform.rotate_x(3.0 * time.delta_seconds());
    }
}
examples/2d/pixel_grid_snap.rs (line 158)
156
157
158
159
160
161
fn rotate(time: Res<Time>, mut transforms: Query<&mut Transform, With<Rotate>>) {
    for mut transform in &mut transforms {
        let dt = time.delta_seconds();
        transform.rotate_z(dt);
    }
}
examples/2d/bounding_2d.rs (line 37)
35
36
37
38
39
fn spin(time: Res<Time>, mut query: Query<&mut Transform, With<Spin>>) {
    for mut transform in query.iter_mut() {
        transform.rotation *= Quat::from_rotation_z(time.delta_seconds() / 5.);
    }
}
examples/games/contributors.rs (line 224)
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
fn gravity(time: Res<Time>, mut velocity_query: Query<&mut Velocity>) {
    let delta = time.delta_seconds();

    for mut velocity in &mut velocity_query {
        velocity.translation.y -= GRAVITY * delta;
    }
}

/// Checks for collisions of contributor-birbs.
///
/// On collision with left-or-right wall it resets the horizontal
/// velocity. On collision with the ground it applies an upwards
/// force.
fn collisions(
    windows: Query<&Window>,
    mut query: Query<(&mut Velocity, &mut Transform), With<Contributor>>,
) {
    let window = windows.single();
    let window_size = window.size();

    let collision_area = Aabb2d::new(Vec2::ZERO, (window_size - SPRITE_SIZE) / 2.);

    // The maximum height the birbs should try to reach is one birb below the top of the window.
    let max_bounce_height = (window_size.y - SPRITE_SIZE * 2.0).max(0.0);
    let min_bounce_height = max_bounce_height * 0.4;

    let mut rng = rand::thread_rng();

    for (mut velocity, mut transform) in &mut query {
        // Clamp the translation to not go out of the bounds
        if transform.translation.y < collision_area.min.y {
            transform.translation.y = collision_area.min.y;

            // How high this birb will bounce.
            let bounce_height = rng.gen_range(min_bounce_height..=max_bounce_height);

            // Apply the velocity that would bounce the birb up to bounce_height.
            velocity.translation.y = (bounce_height * GRAVITY * 2.).sqrt();
        }

        // Birbs might hit the ceiling if the window is resized.
        // If they do, bounce them.
        if transform.translation.y > collision_area.max.y {
            transform.translation.y = collision_area.max.y;
            velocity.translation.y *= -1.0;
        }

        // On side walls flip the horizontal velocity
        if transform.translation.x < collision_area.min.x {
            transform.translation.x = collision_area.min.x;
            velocity.translation.x *= -1.0;
            velocity.rotation *= -1.0;
        }
        if transform.translation.x > collision_area.max.x {
            transform.translation.x = collision_area.max.x;
            velocity.translation.x *= -1.0;
            velocity.rotation *= -1.0;
        }
    }
}

/// Apply velocity to positions and rotations.
fn movement(time: Res<Time>, mut query: Query<(&Velocity, &mut Transform)>) {
    let delta = time.delta_seconds();

    for (velocity, mut transform) in &mut query {
        transform.translation += delta * velocity.translation;
        transform.rotate_z(velocity.rotation * delta);
    }
}

pub fn delta_seconds_f64(&self) -> f64

Returns how much time has advanced since the last update, as f64 seconds.

Examples found in repository?
examples/ui/text_debug.rs (line 207)
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
fn change_text_system(
    time: Res<Time>,
    diagnostics: Res<DiagnosticsStore>,
    mut query: Query<&mut Text, With<TextChanges>>,
) {
    for mut text in &mut query {
        let mut fps = 0.0;
        if let Some(fps_diagnostic) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) {
            if let Some(fps_smoothed) = fps_diagnostic.smoothed() {
                fps = fps_smoothed;
            }
        }

        let mut frame_time = time.delta_seconds_f64();
        if let Some(frame_time_diagnostic) =
            diagnostics.get(&FrameTimeDiagnosticsPlugin::FRAME_TIME)
        {
            if let Some(frame_time_smoothed) = frame_time_diagnostic.smoothed() {
                frame_time = frame_time_smoothed;
            }
        }

        text.sections[0].value = format!(
            "This text changes in the bottom right - {fps:.1} fps, {frame_time:.3} ms/frame",
        );

        text.sections[2].value = format!("{fps:.1}");

        text.sections[4].value = format!("{frame_time:.3}");
    }
}
More examples
Hide additional examples
examples/stress_tests/bevymark.rs (line 322)
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
fn mouse_handler(
    mut commands: Commands,
    args: Res<Args>,
    time: Res<Time>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    windows: Query<&Window>,
    bird_resources: ResMut<BirdResources>,
    mut counter: ResMut<BevyCounter>,
    mut rng: Local<Option<ChaCha8Rng>>,
    mut wave: Local<usize>,
) {
    if rng.is_none() {
        // We're seeding the PRNG here to make this example deterministic for testing purposes.
        // This isn't strictly required in practical use unless you need your app to be deterministic.
        *rng = Some(ChaCha8Rng::seed_from_u64(42));
    }
    let rng = rng.as_mut().unwrap();
    let window = windows.single();

    if mouse_button_input.just_released(MouseButton::Left) {
        counter.color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
    }

    if mouse_button_input.pressed(MouseButton::Left) {
        let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_seconds_f64()) as usize;
        spawn_birds(
            &mut commands,
            args.into_inner(),
            &window.resolution,
            &mut counter,
            spawn_count,
            bird_resources.into_inner(),
            None,
            *wave,
        );
        *wave += 1;
    }
}

pub fn elapsed(&self) -> Duration

Returns how much time has advanced since startup, as Duration.

Examples found in repository?
examples/time/time.rs (line 87)
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
fn print_real_time(time: Res<Time<Real>>) {
    println!(
        "PreUpdate: this is real time clock, delta is {:?} and elapsed is {:?}",
        time.delta(),
        time.elapsed()
    );
}

fn print_fixed_time(time: Res<Time>) {
    println!(
        "FixedUpdate: this is generic time clock inside fixed, delta is {:?} and elapsed is {:?}",
        time.delta(),
        time.elapsed()
    );
}

fn print_time(time: Res<Time>) {
    println!(
        "Update: this is generic time clock, delta is {:?} and elapsed is {:?}",
        time.delta(),
        time.elapsed()
    );
}
More examples
Hide additional examples
examples/scene/scene.rs (line 48)
45
46
47
48
49
50
51
    fn from_world(world: &mut World) -> Self {
        let time = world.resource::<Time>();
        ComponentB {
            _time_since_startup: time.elapsed(),
            value: "Default Value".to_string(),
        }
    }
examples/window/window_settings.rs (line 132)
128
129
130
131
132
133
134
fn change_title(mut windows: Query<&mut Window>, time: Res<Time>) {
    let mut window = windows.single_mut();
    window.title = format!(
        "Seconds since startup: {}",
        time.elapsed().as_secs_f32().round()
    );
}

pub fn elapsed_seconds(&self) -> f32

Returns how much time has advanced since startup, as f32 seconds.

Note: This is a monotonically increasing value. It’s precision will degrade over time. If you need an f32 but that precision loss is unacceptable, use elapsed_seconds_wrapped.

Examples found in repository?
examples/audio/audio_control.rs (line 28)
26
27
28
29
30
fn update_speed(music_controller: Query<&AudioSink, With<MyMusic>>, time: Res<Time>) {
    if let Ok(sink) = music_controller.get_single() {
        sink.set_speed(((time.elapsed_seconds() / 5.0).sin() + 1.0).max(0.1));
    }
}
More examples
Hide additional examples
examples/animation/custom_skinned_mesh.rs (line 170)
168
169
170
171
172
fn joint_animation(time: Res<Time>, mut query: Query<&mut Transform, With<AnimatedJoint>>) {
    for mut transform in &mut query {
        transform.rotation = Quat::from_rotation_z(FRAC_PI_2 * time.elapsed_seconds().sin());
    }
}
examples/stress_tests/text_pipeline.rs (line 76)
75
76
77
78
79
80
fn update_text_bounds(time: Res<Time>, mut text_bounds_query: Query<&mut Text2dBounds>) {
    let width = (1. + time.elapsed_seconds().sin()) * 600.0;
    for mut text_bounds in text_bounds_query.iter_mut() {
        text_bounds.size.x = width;
    }
}
examples/shader/shader_prepass.rs (line 191)
189
190
191
192
193
194
fn rotate(mut q: Query<&mut Transform, With<Rotates>>, time: Res<Time>) {
    for mut t in q.iter_mut() {
        let rot = (time.elapsed_seconds().sin() * 0.5 + 0.5) * std::f32::consts::PI * 2.0;
        t.rotation = Quat::from_rotation_z(rot);
    }
}
examples/3d/transparency_3d.rs (line 119)
118
119
120
121
122
123
pub fn fade_transparency(time: Res<Time>, mut materials: ResMut<Assets<StandardMaterial>>) {
    let alpha = (time.elapsed_seconds().sin() / 2.0) + 0.5;
    for (_, material) in materials.iter_mut() {
        material.base_color.set_alpha(alpha);
    }
}
examples/ecs/fixed_timestep.rs (line 21)
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
fn frame_update(mut last_time: Local<f32>, time: Res<Time>) {
    // Default `Time` is `Time<Virtual>` here
    info!(
        "time since last frame_update: {}",
        time.elapsed_seconds() - *last_time
    );
    *last_time = time.elapsed_seconds();
}

fn fixed_update(mut last_time: Local<f32>, time: Res<Time>, fixed_time: Res<Time<Fixed>>) {
    // Default `Time`is `Time<Fixed>` here
    info!(
        "time since last fixed_update: {}\n",
        time.elapsed_seconds() - *last_time
    );

    info!("fixed timestep: {}\n", time.delta_seconds());
    // If we want to see the overstep, we need to access `Time<Fixed>` specifically
    info!(
        "time accrued toward next fixed_update: {}\n",
        fixed_time.overstep().as_secs_f32()
    );
    *last_time = time.elapsed_seconds();
}

pub fn elapsed_seconds_f64(&self) -> f64

Returns how much time has advanced since startup, as f64 seconds.

pub fn elapsed_wrapped(&self) -> Duration

Returns how much time has advanced since startup modulo the wrap_period, as Duration.

pub fn elapsed_seconds_wrapped(&self) -> f32

Returns how much time has advanced since startup modulo the wrap_period, as f32 seconds.

This method is intended for applications (e.g. shaders) that require an f32 value but suffer from the gradual precision loss of elapsed_seconds.

pub fn elapsed_seconds_wrapped_f64(&self) -> f64

Returns how much time has advanced since startup modulo the wrap_period, as f64 seconds.

pub fn context(&self) -> &T

Returns a reference to the context of this specific clock.

pub fn context_mut(&mut self) -> &mut T

Returns a mutable reference to the context of this specific clock.

pub fn as_generic(&self) -> Time

Returns a copy of this clock as fully generic clock without context.

§

impl Time<Virtual>

pub fn from_max_delta(max_delta: Duration) -> Time<Virtual>

Create new virtual clock with given maximum delta step Duration

§Panics

Panics if max_delta is zero.

Examples found in repository?
examples/time/time.rs (line 110)
107
108
109
110
111
112
113
114
115
116
117
fn main() {
    App::new()
        .add_plugins(MinimalPlugins)
        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
        .add_systems(PreUpdate, print_real_time)
        .add_systems(FixedUpdate, print_fixed_time)
        .add_systems(Update, print_time)
        .set_runner(runner)
        .run();
}

pub fn max_delta(&self) -> Duration

Returns the maximum amount of time that can be added to this clock by a single update, as Duration.

This is the maximum value Self::delta() will return and also to maximum time Self::elapsed() will be increased by in a single update.

This ensures that even if no updates happen for an extended amount of time, the clock will not have a sudden, huge advance all at once. This also indirectly limits the maximum number of fixed update steps that can run in a single update.

The default value is 250 milliseconds.

pub fn set_max_delta(&mut self, max_delta: Duration)

Sets the maximum amount of time that can be added to this clock by a single update, as Duration.

This is the maximum value Self::delta() will return and also to maximum time Self::elapsed() will be increased by in a single update.

This is used to ensure that even if the game freezes for a few seconds, or is suspended for hours or even days, the virtual clock doesn’t suddenly jump forward for that full amount, which would likely cause gameplay bugs or having to suddenly simulate all the intervening time.

If no updates happen for an extended amount of time, this limit prevents having a sudden, huge advance all at once. This also indirectly limits the maximum number of fixed update steps that can run in a single update.

The default value is 250 milliseconds. If you want to disable this feature, set the value to Duration::MAX.

§Panics

Panics if max_delta is zero.

pub fn relative_speed(&self) -> f32

Returns the speed the clock advances relative to your system clock, as f32. This is known as “time scaling” or “time dilation” in other engines.

Examples found in repository?
examples/time/virtual_time.rs (line 177)
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
fn change_time_speed<const DELTA: i8>(mut time: ResMut<Time<Virtual>>) {
    let time_speed = (time.relative_speed() + DELTA as f32)
        .round()
        .clamp(0.25, 5.);

    // set the speed of the virtual time to speed it up or slow it down
    time.set_relative_speed(time_speed);
}

/// pause or resume `Relative` time
fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
    if time.is_paused() {
        time.unpause();
    } else {
        time.pause();
    }
}

/// Update the `Real` time info text
fn update_real_time_info_text(time: Res<Time<Real>>, mut query: Query<&mut Text, With<RealTime>>) {
    for mut text in &mut query {
        text.sections[0].value = format!(
            "REAL TIME\nElapsed: {:.1}\nDelta: {:.5}\n",
            time.elapsed_seconds(),
            time.delta_seconds(),
        );
    }
}

/// Update the `Virtual` time info text
fn update_virtual_time_info_text(
    time: Res<Time<Virtual>>,
    mut query: Query<&mut Text, With<VirtualTime>>,
) {
    for mut text in &mut query {
        text.sections[0].value = format!(
            "VIRTUAL TIME\nElapsed: {:.1}\nDelta: {:.5}\nSpeed: {:.2}",
            time.elapsed_seconds(),
            time.delta_seconds(),
            time.relative_speed()
        );
    }
}

pub fn relative_speed_f64(&self) -> f64

Returns the speed the clock advances relative to your system clock, as f64. This is known as “time scaling” or “time dilation” in other engines.

pub fn effective_speed(&self) -> f32

Returns the speed the clock advanced relative to your system clock in this update, as f32.

Returns 0.0 if the game was paused or what the relative_speed value was at the start of this update.

pub fn effective_speed_f64(&self) -> f64

Returns the speed the clock advanced relative to your system clock in this update, as f64.

Returns 0.0 if the game was paused or what the relative_speed value was at the start of this update.

pub fn set_relative_speed(&mut self, ratio: f32)

Sets the speed the clock advances relative to your system clock, given as an f32.

For example, setting this to 2.0 will make the clock advance twice as fast as your system clock.

§Panics

Panics if ratio is negative or not finite.

Examples found in repository?
examples/time/time.rs (line 50)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
fn runner(mut app: App) {
    banner();
    help();
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        if let Err(err) = line {
            println!("read err: {:#}", err);
            break;
        }
        match line.unwrap().as_str() {
            "" => {
                app.update();
            }
            "f" => {
                println!("FAST: setting relative speed to 2x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(2.0);
            }
            "n" => {
                println!("NORMAL: setting relative speed to 1x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(1.0);
            }
            "s" => {
                println!("SLOW: setting relative speed to 0.5x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(0.5);
            }
            "p" => {
                println!("PAUSE: pausing virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().pause();
            }
            "u" => {
                println!("UNPAUSE: resuming virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
            }
            "q" => {
                println!("QUITTING!");
                break;
            }
            _ => {
                help();
            }
        }
    }
}
More examples
Hide additional examples
examples/time/virtual_time.rs (line 46)
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut time: ResMut<Time<Virtual>>) {
    // start with double `Virtual` time resulting in one of the sprites moving at twice the speed
    // of the other sprite which moves based on `Real` (unscaled) time
    time.set_relative_speed(2.);

    commands.spawn(Camera2dBundle::default());

    let virtual_color = GOLD.into();
    let sprite_scale = Vec2::splat(0.5).extend(1.);
    let texture_handle = asset_server.load("branding/icon.png");

    // the sprite moving based on real time
    commands.spawn((
        SpriteBundle {
            texture: texture_handle.clone(),
            transform: Transform::from_scale(sprite_scale),
            ..default()
        },
        RealTime,
    ));

    // the sprite moving based on virtual time
    commands.spawn((
        SpriteBundle {
            texture: texture_handle,
            sprite: Sprite {
                color: virtual_color,
                ..default()
            },
            transform: Transform {
                scale: sprite_scale,
                translation: Vec3::new(0., -160., 0.),
                ..default()
            },
            ..default()
        },
        VirtualTime,
    ));

    // info UI
    let font_size = 40.;

    commands
        .spawn(NodeBundle {
            style: Style {
                display: Display::Flex,
                justify_content: JustifyContent::SpaceBetween,
                width: Val::Percent(100.),
                position_type: PositionType::Absolute,
                top: Val::Px(0.),
                padding: UiRect::all(Val::Px(20.0)),
                ..default()
            },
            ..default()
        })
        .with_children(|builder| {
            // real time info
            builder.spawn((
                TextBundle::from_section(
                    "",
                    TextStyle {
                        font_size,
                        ..default()
                    },
                ),
                RealTime,
            ));

            // keybindings
            builder.spawn(
                TextBundle::from_section(
                    "CONTROLS\nUn/Pause: Space\nSpeed+: Up\nSpeed-: Down",
                    TextStyle {
                        font_size,
                        color: Color::srgb(0.85, 0.85, 0.85),
                        ..default()
                    },
                )
                .with_text_justify(JustifyText::Center),
            );

            // virtual time info
            builder.spawn((
                TextBundle::from_section(
                    "",
                    TextStyle {
                        font_size,
                        color: virtual_color,
                        ..default()
                    },
                )
                .with_text_justify(JustifyText::Right),
                VirtualTime,
            ));
        });
}

/// Move sprites using `Real` (unscaled) time
fn move_real_time_sprites(
    mut sprite_query: Query<&mut Transform, (With<Sprite>, With<RealTime>)>,
    // `Real` time which is not scaled or paused
    time: Res<Time<Real>>,
) {
    for mut transform in sprite_query.iter_mut() {
        // move roughly half the screen in a `Real` second
        // when the time is scaled the speed is going to change
        // and the sprite will stay still the time is paused
        transform.translation.x = get_sprite_translation_x(time.elapsed_seconds());
    }
}

/// Move sprites using `Virtual` (scaled) time
fn move_virtual_time_sprites(
    mut sprite_query: Query<&mut Transform, (With<Sprite>, With<VirtualTime>)>,
    // the default `Time` is either `Time<Virtual>` in regular systems
    // or `Time<Fixed>` in fixed timestep systems so `Time::delta()`,
    // `Time::elapsed()` will return the appropriate values either way
    time: Res<Time>,
) {
    for mut transform in sprite_query.iter_mut() {
        // move roughly half the screen in a `Virtual` second
        // when time is scaled using `Time<Virtual>::set_relative_speed` it's going
        // to move at a different pace and the sprite will stay still when time is
        // `Time<Virtual>::is_paused()`
        transform.translation.x = get_sprite_translation_x(time.elapsed_seconds());
    }
}

fn get_sprite_translation_x(elapsed: f32) -> f32 {
    elapsed.sin() * 500.
}

/// Update the speed of `Time<Virtual>.` by `DELTA`
fn change_time_speed<const DELTA: i8>(mut time: ResMut<Time<Virtual>>) {
    let time_speed = (time.relative_speed() + DELTA as f32)
        .round()
        .clamp(0.25, 5.);

    // set the speed of the virtual time to speed it up or slow it down
    time.set_relative_speed(time_speed);
}

pub fn set_relative_speed_f64(&mut self, ratio: f64)

Sets the speed the clock advances relative to your system clock, given as an f64.

For example, setting this to 2.0 will make the clock advance twice as fast as your system clock.

§Panics

Panics if ratio is negative or not finite.

pub fn pause(&mut self)

Stops the clock, preventing it from advancing until resumed.

Examples found in repository?
examples/time/virtual_time.rs (line 190)
186
187
188
189
190
191
192
fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
    if time.is_paused() {
        time.unpause();
    } else {
        time.pause();
    }
}
More examples
Hide additional examples
examples/time/time.rs (line 66)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
fn runner(mut app: App) {
    banner();
    help();
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        if let Err(err) = line {
            println!("read err: {:#}", err);
            break;
        }
        match line.unwrap().as_str() {
            "" => {
                app.update();
            }
            "f" => {
                println!("FAST: setting relative speed to 2x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(2.0);
            }
            "n" => {
                println!("NORMAL: setting relative speed to 1x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(1.0);
            }
            "s" => {
                println!("SLOW: setting relative speed to 0.5x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(0.5);
            }
            "p" => {
                println!("PAUSE: pausing virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().pause();
            }
            "u" => {
                println!("UNPAUSE: resuming virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
            }
            "q" => {
                println!("QUITTING!");
                break;
            }
            _ => {
                help();
            }
        }
    }
}

pub fn unpause(&mut self)

Resumes the clock if paused.

Examples found in repository?
examples/time/virtual_time.rs (line 188)
186
187
188
189
190
191
192
fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
    if time.is_paused() {
        time.unpause();
    } else {
        time.pause();
    }
}
More examples
Hide additional examples
examples/time/time.rs (line 70)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
fn runner(mut app: App) {
    banner();
    help();
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        if let Err(err) = line {
            println!("read err: {:#}", err);
            break;
        }
        match line.unwrap().as_str() {
            "" => {
                app.update();
            }
            "f" => {
                println!("FAST: setting relative speed to 2x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(2.0);
            }
            "n" => {
                println!("NORMAL: setting relative speed to 1x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(1.0);
            }
            "s" => {
                println!("SLOW: setting relative speed to 0.5x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(0.5);
            }
            "p" => {
                println!("PAUSE: pausing virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().pause();
            }
            "u" => {
                println!("UNPAUSE: resuming virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
            }
            "q" => {
                println!("QUITTING!");
                break;
            }
            _ => {
                help();
            }
        }
    }
}

pub fn is_paused(&self) -> bool

Returns true if the clock is currently paused.

Examples found in repository?
examples/time/virtual_time.rs (line 187)
186
187
188
189
190
191
192
fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
    if time.is_paused() {
        time.unpause();
    } else {
        time.pause();
    }
}

pub fn was_paused(&self) -> bool

Returns true if the clock was paused at the start of this update.

Trait Implementations§

§

impl<T> Clone for Time<T>
where T: Clone + Default,

§

fn clone(&self) -> Time<T>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<T> Debug for Time<T>
where T: Debug + Default,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Default for Time<T>
where T: Default,

§

fn default() -> Time<T>

Returns the “default value” for a type. Read more
§

impl<T> FromReflect for Time<T>
where T: Default + TypePath + FromReflect + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + RegisterForReflection, f32: FromReflect + TypePath + RegisterForReflection, f64: FromReflect + TypePath + RegisterForReflection,

§

fn from_reflect(reflect: &(dyn Reflect + 'static)) -> Option<Time<T>>

Constructs a concrete instance of Self from a reflected value.
§

fn take_from_reflect( reflect: Box<dyn Reflect> ) -> Result<Self, Box<dyn Reflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
§

impl<T> GetTypeRegistration for Time<T>
where T: Default + TypePath + FromReflect + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + RegisterForReflection, f32: FromReflect + TypePath + RegisterForReflection, f64: FromReflect + TypePath + RegisterForReflection,

§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
§

impl<T> Reflect for Time<T>
where T: Default + TypePath + FromReflect + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + RegisterForReflection, f32: FromReflect + TypePath + RegisterForReflection, f64: FromReflect + TypePath + RegisterForReflection,

§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
§

fn into_any(self: Box<Time<T>>) -> Box<dyn Any>

Returns the value as a Box<dyn Any>.
§

fn as_any(&self) -> &(dyn Any + 'static)

Returns the value as a &dyn Any.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Returns the value as a &mut dyn Any.
§

fn into_reflect(self: Box<Time<T>>) -> Box<dyn Reflect>

Casts this type to a boxed reflected value.
§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a reflected value.
§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable reflected value.
§

fn clone_value(&self) -> Box<dyn Reflect>

Clones the value as a Reflect trait object. Read more
§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
§

fn apply(&mut self, value: &(dyn Reflect + 'static))

Applies a reflected value to this value. Read more
§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
§

fn reflect_owned(self: Box<Time<T>>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
§

fn reflect_partial_eq(&self, value: &(dyn Reflect + 'static)) -> Option<bool>

Returns a “partial equality” comparison result. Read more
§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
§

fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Debug formatter for the value. Read more
§

fn serializable(&self) -> Option<Serializable<'_>>

Returns a serializable version of the value. Read more
§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
§

impl<T> Struct for Time<T>
where T: Default + TypePath + FromReflect + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + RegisterForReflection, f32: FromReflect + TypePath + RegisterForReflection, f64: FromReflect + TypePath + RegisterForReflection,

§

fn field(&self, name: &str) -> Option<&(dyn Reflect + 'static)>

Returns a reference to the value of the field named name as a &dyn Reflect.
§

fn field_mut(&mut self, name: &str) -> Option<&mut (dyn Reflect + 'static)>

Returns a mutable reference to the value of the field named name as a &mut dyn Reflect.
§

fn field_at(&self, index: usize) -> Option<&(dyn Reflect + 'static)>

Returns a reference to the value of the field with index index as a &dyn Reflect.
§

fn field_at_mut(&mut self, index: usize) -> Option<&mut (dyn Reflect + 'static)>

Returns a mutable reference to the value of the field with index index as a &mut dyn Reflect.
§

fn name_at(&self, index: usize) -> Option<&str>

Returns the name of the field with index index.
§

fn field_len(&self) -> usize

Returns the number of fields in the struct.
§

fn iter_fields(&self) -> FieldIter<'_>

Returns an iterator over the values of the reflectable fields for this struct.
§

fn clone_dynamic(&self) -> DynamicStruct

Clones the struct into a DynamicStruct.
§

impl<T> TypePath for Time<T>
where T: Default + TypePath, Time<T>: Any + Send + Sync,

§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
§

impl<T> Typed for Time<T>
where T: Default + TypePath + FromReflect + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + RegisterForReflection, f32: FromReflect + TypePath + RegisterForReflection, f64: FromReflect + TypePath + RegisterForReflection,

§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.
§

impl<T> Copy for Time<T>
where T: Copy + Default,

§

impl<T> Resource for Time<T>
where T: Default, Time<T>: Send + Sync + 'static,

Auto Trait Implementations§

§

impl<T> Freeze for Time<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Time<T>
where T: RefUnwindSafe,

§

impl<T> Send for Time<T>
where T: Send,

§

impl<T> Sync for Time<T>
where T: Sync,

§

impl<T> Unpin for Time<T>
where T: Unpin,

§

impl<T> UnwindSafe for Time<T>
where T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
§

impl<T> DynamicTypePath for T
where T: TypePath,

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

§

impl<T> FromWorld for T
where T: Default,

§

fn from_world(_world: &mut World) -> T

Creates Self using data from the given World.
§

impl<S> GetField for S
where S: Struct,

§

fn get_field<T>(&self, name: &str) -> Option<&T>
where T: Reflect,

Returns a reference to the value of the field named name, downcast to T.
§

fn get_field_mut<T>(&mut self, name: &str) -> Option<&mut T>
where T: Reflect,

Returns a mutable reference to the value of the field named name, downcast to T.
§

impl<T> GetPath for T
where T: Reflect + ?Sized,

§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p> ) -> Result<&(dyn Reflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p> ) -> Result<&mut (dyn Reflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
§

fn path<'p, T>( &self, path: impl ReflectPath<'p> ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p> ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> NoneValue for T
where T: Default,

§

type NoneType = T

§

fn null_value() -> T

The none-equivalent value.
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

§

fn clone_type_data(&self) -> Box<dyn TypeData>

§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<T> ConditionalSend for T
where T: Send,

§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

§

impl<T> Settings for T
where T: 'static + Send + Sync,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,