Skip to main content

Time

Struct Time 

Source
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_secs() and elapsed_secs(), and also in seconds as f64 via delta_secs_f64() and elapsed_secs_f64().

Since elapsed_secs() 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_secs_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(Message)]
struct Pause(bool);

fn pause_system(mut time: ResMut<Time<Virtual>>, mut pause_reader: MessageReader<Pause>) {
    for pause in pause_reader.read() {
        if pause.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§

Source§

impl Time<Fixed>

Source

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 115)
111fn main() {
112    App::new()
113        .add_plugins(MinimalPlugins)
114        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
115        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
116        .add_systems(PreUpdate, print_real_time)
117        .add_systems(FixedUpdate, print_fixed_time)
118        .add_systems(Update, print_time)
119        .set_runner(runner)
120        .run();
121}
More examples
Hide additional examples
examples/stress_tests/bevymark_3d.rs (lines 134-136)
96fn main() {
97    // `from_env` panics on the web
98    #[cfg(not(target_arch = "wasm32"))]
99    let args: Args = argh::from_env();
100    #[cfg(target_arch = "wasm32")]
101    let args = Args::from_args(&[], &[]).unwrap();
102
103    App::new()
104        .add_plugins((
105            DefaultPlugins.set(WindowPlugin {
106                primary_window: Some(Window {
107                    title: "BevyMark 3D".into(),
108                    resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
109                    present_mode: PresentMode::AutoNoVsync,
110                    ..default()
111                }),
112                ..default()
113            }),
114            FrameTimeDiagnosticsPlugin::default(),
115            LogDiagnosticsPlugin::default(),
116        ))
117        .insert_resource(WinitSettings::continuous())
118        .insert_resource(args)
119        .insert_resource(BevyCounter {
120            count: 0,
121            color: Color::WHITE,
122        })
123        .add_systems(Startup, setup)
124        .add_systems(FixedUpdate, scheduled_spawner)
125        .add_systems(
126            Update,
127            (
128                mouse_handler,
129                movement_system,
130                collision_system,
131                counter_system,
132            ),
133        )
134        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs_f32(
135            FIXED_TIMESTEP,
136        )))
137        .run();
138}
examples/stress_tests/bevymark.rs (lines 164-166)
125fn main() {
126    // `from_env` panics on the web
127    #[cfg(not(target_arch = "wasm32"))]
128    let args: Args = argh::from_env();
129    #[cfg(target_arch = "wasm32")]
130    let args = Args::from_args(&[], &[]).unwrap();
131
132    App::new()
133        .add_plugins((
134            DefaultPlugins.set(WindowPlugin {
135                primary_window: Some(Window {
136                    title: "BevyMark".into(),
137                    resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
138                    present_mode: PresentMode::AutoNoVsync,
139                    ..default()
140                }),
141                ..default()
142            }),
143            FrameTimeDiagnosticsPlugin::default(),
144            LogDiagnosticsPlugin::default(),
145        ))
146        .insert_resource(StaticTransformOptimizations::Disabled)
147        .insert_resource(WinitSettings::continuous())
148        .insert_resource(args)
149        .insert_resource(BevyCounter {
150            count: 0,
151            color: Color::WHITE,
152        })
153        .add_systems(Startup, setup)
154        .add_systems(FixedUpdate, scheduled_spawner)
155        .add_systems(
156            Update,
157            (
158                mouse_handler,
159                movement_system,
160                collision_system,
161                counter_system,
162            ),
163        )
164        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs_f32(
165            FIXED_TIMESTEP,
166        )))
167        .run();
168}
Source

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/async_tasks/external_source_external_thread.rs (line 16)
9fn main() {
10    App::new()
11        .add_message::<StreamMessage>()
12        .add_plugins(DefaultPlugins)
13        .add_systems(Startup, setup)
14        .add_systems(Update, (spawn_text, move_text))
15        .add_systems(FixedUpdate, read_stream)
16        .insert_resource(Time::<Fixed>::from_seconds(0.5))
17        .run();
18}
More examples
Hide additional examples
examples/ecs/fixed_timestep.rs (line 13)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        // this system will run once every update (it should match your screen's refresh rate)
9        .add_systems(Update, frame_update)
10        // add our system to the fixed timestep schedule
11        .add_systems(FixedUpdate, fixed_update)
12        // configure our fixed timestep schedule to run twice a second
13        .insert_resource(Time::<Fixed>::from_seconds(0.5))
14        .run();
15}
Source

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)
7fn main() {
8    App::new()
9        .add_plugins(DefaultPlugins)
10        .insert_resource(Time::<Fixed>::from_hz(60.0))
11        .add_systems(Startup, setup)
12        .add_systems(
13            FixedUpdate,
14            (
15                player_movement_system,
16                snap_to_player_system,
17                rotate_to_player_system,
18            ),
19        )
20        .run();
21}
More examples
Hide additional examples
examples/2d/cpu_draw.rs (line 25)
18fn main() {
19    App::new()
20        .add_plugins(DefaultPlugins)
21        // In this example, we will use a fixed timestep to draw a pattern on the screen
22        // one pixel at a time, so the pattern will gradually emerge over time, and
23        // the speed at which it appears is not tied to the framerate.
24        // Let's make the fixed update very fast, so it doesn't take too long. :)
25        .insert_resource(Time::<Fixed>::from_hz(1024.0))
26        .add_systems(Startup, setup)
27        .add_systems(FixedUpdate, draw)
28        .run();
29}
Source

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 81)
38fn generate_bodies(
39    time: Res<Time<Fixed>>,
40    mut commands: Commands,
41    mut meshes: ResMut<Assets<Mesh>>,
42    mut materials: ResMut<Assets<StandardMaterial>>,
43) {
44    let mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap());
45
46    let color_range = 0.5..1.0;
47    let vel_range = -0.5..0.5;
48
49    // We're seeding the PRNG here to make this example deterministic for testing purposes.
50    // This isn't strictly required in practical use unless you need your app to be deterministic.
51    let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
52    for _ in 0..NUM_BODIES {
53        let radius: f32 = rng.random_range(0.1..0.7);
54        let mass_value = FloatPow::cubed(radius) * 10.;
55
56        let position = Vec3::new(
57            rng.random_range(-1.0..1.0),
58            rng.random_range(-1.0..1.0),
59            rng.random_range(-1.0..1.0),
60        )
61        .normalize()
62            * ops::cbrt(rng.random_range(0.2f32..1.0))
63            * 15.;
64
65        commands.spawn((
66            BodyBundle {
67                mesh: Mesh3d(mesh.clone()),
68                material: MeshMaterial3d(materials.add(Color::srgb(
69                    rng.random_range(color_range.clone()),
70                    rng.random_range(color_range.clone()),
71                    rng.random_range(color_range.clone()),
72                ))),
73                mass: Mass(mass_value),
74                acceleration: Acceleration(Vec3::ZERO),
75                last_pos: LastPos(
76                    position
77                        - Vec3::new(
78                            rng.random_range(vel_range.clone()),
79                            rng.random_range(vel_range.clone()),
80                            rng.random_range(vel_range.clone()),
81                        ) * time.timestep().as_secs_f32(),
82                ),
83            },
84            Transform {
85                translation: position,
86                scale: Vec3::splat(radius),
87                ..default()
88            },
89        ));
90    }
91
92    // add bigger "star" body in the center
93    let star_radius = 1.;
94    commands
95        .spawn((
96            BodyBundle {
97                mesh: Mesh3d(meshes.add(Sphere::new(1.0).mesh().ico(5).unwrap())),
98                material: MeshMaterial3d(materials.add(StandardMaterial {
99                    base_color: ORANGE_RED.into(),
100                    emissive: LinearRgba::from(ORANGE_RED) * 2.,
101                    ..default()
102                })),
103
104                mass: Mass(500.0),
105                ..default()
106            },
107            Transform::from_scale(Vec3::splat(star_radius)),
108            Star,
109        ))
110        .with_child(PointLight {
111            color: Color::WHITE,
112            range: 100.0,
113            radius: star_radius,
114            ..default()
115        });
116    commands.spawn((
117        Camera3d::default(),
118        Transform::from_xyz(0.0, 10.5, -30.0).looking_at(Vec3::ZERO, Vec3::Y),
119    ));
120}
Source

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.

Source

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.

Source

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.

Source

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)
26fn fixed_update(mut last_time: Local<f32>, time: Res<Time>, fixed_time: Res<Time<Fixed>>) {
27    // Default `Time`is `Time<Fixed>` here
28    info!(
29        "time since last fixed_update: {}\n",
30        time.elapsed_secs() - *last_time
31    );
32
33    info!("fixed timestep: {}\n", time.delta_secs());
34    // If we want to see the overstep, we need to access `Time<Fixed>` specifically
35    info!(
36        "time accrued toward next fixed_update: {}\n",
37        fixed_time.overstep().as_secs_f32()
38    );
39    *last_time = time.elapsed_secs();
40}
Source

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

Increase the overstep time accumulated towards new steps.

This method is provided for use in tests. Ordinarily, the run_fixed_main_schedule system is responsible for calculating the overstep.

Source

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.

Source

pub fn overstep_fraction(&self) -> f32

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

Examples found in repository?
examples/movement/physics_in_fixed_timestep.rs (line 404)
390fn interpolate_rendered_transform(
391    fixed_time: Res<Time<Fixed>>,
392    mut query: Query<(
393        &mut Transform,
394        &PhysicalTranslation,
395        &PreviousPhysicalTranslation,
396    )>,
397) {
398    for (mut transform, current_physical_translation, previous_physical_translation) in
399        query.iter_mut()
400    {
401        let previous = previous_physical_translation.0;
402        let current = current_physical_translation.0;
403        // The overstep fraction is a value between 0 and 1 that tells us how far we are between two fixed timesteps.
404        let alpha = fixed_time.overstep_fraction();
405
406        let rendered_translation = previous.lerp(current, alpha);
407        transform.translation = rendered_translation;
408    }
409}
Source

pub fn overstep_fraction_f64(&self) -> f64

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

Source§

impl Time<Real>

Source

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

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

Source

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.

Source

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.

Source

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.

Source

pub fn startup(&self) -> Instant

Returns the Instant the clock was created.

This usually represents when the app was started.

Source

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.

Source

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.

Source§

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

Source

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

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

Source

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.

Source

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().

Source

pub fn wrap_period(&self) -> Duration

Returns the modulus used to calculate elapsed_wrapped.

Note: The default modulus is one hour.

Source

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.

Source

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 49)
48fn print_message_system(mut state: ResMut<PrintMessageState>, time: Res<Time>) {
49    if state.timer.tick(time.delta()).is_finished() {
50        info!("{}", state.message);
51    }
52}
More examples
Hide additional examples
examples/time/time.rs (line 90)
87fn print_real_time(time: Res<Time<Real>>) {
88    println!(
89        "PreUpdate: this is real time clock, delta is {:?} and elapsed is {:?}",
90        time.delta(),
91        time.elapsed()
92    );
93}
94
95fn print_fixed_time(time: Res<Time>) {
96    println!(
97        "FixedUpdate: this is generic time clock inside fixed, delta is {:?} and elapsed is {:?}",
98        time.delta(),
99        time.elapsed()
100    );
101}
102
103fn print_time(time: Res<Time>) {
104    println!(
105        "Update: this is generic time clock, delta is {:?} and elapsed is {:?}",
106        time.delta(),
107        time.elapsed()
108    );
109}
examples/stress_tests/many_sprites.rs (line 120)
119fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) {
120    timer.tick(time.delta());
121
122    if timer.just_finished() {
123        info!("Sprites: {}", sprites.iter().count());
124    }
125}
examples/stress_tests/many_lights.rs (line 143)
142fn print_light_count(time: Res<Time>, mut timer: Local<PrintingTimer>, lights: Query<&PointLight>) {
143    timer.0.tick(time.delta());
144
145    if timer.0.just_finished() {
146        info!("Lights: {}", lights.iter().len());
147    }
148}
149
150struct LogVisibleLights;
151
152impl Plugin for LogVisibleLights {
153    fn build(&self, app: &mut App) {
154        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
155            return;
156        };
157
158        render_app.add_systems(
159            Render,
160            print_visible_light_count.in_set(RenderSystems::Prepare),
161        );
162    }
163}
164
165// System for printing the number of meshes on every tick of the timer
166fn print_visible_light_count(
167    time: Res<Time>,
168    mut timer: Local<PrintingTimer>,
169    visible: Query<&ExtractedPointLight>,
170    global_clusterable_object_meta: Res<GlobalClusterableObjectMeta>,
171) {
172    timer.0.tick(time.delta());
173
174    if timer.0.just_finished() {
175        // Note that it's not generally a safe assumption that the number of
176        // lights equals the number of clusterable objects, since some objects
177        // other than lights are clusterable. However, in this specific example,
178        // the only clusterable objects are lights.
179        info!(
180            "Visible Lights: {}, Rendered Lights: {}",
181            visible.iter().len(),
182            global_clusterable_object_meta.entity_to_index.len()
183        );
184    }
185}
examples/ecs/generic_system.rs (line 68)
66fn print_text_system(time: Res<Time>, mut query: Query<(&mut PrinterTick, &TextToPrint)>) {
67    for (mut timer, text) in &mut query {
68        if timer.tick(time.delta()).just_finished() {
69            info!("{}", text.0);
70        }
71    }
72}
examples/time/timers.rs (line 50)
48fn print_when_completed(time: Res<Time>, mut query: Query<&mut PrintOnCompletionTimer>) {
49    for mut timer in &mut query {
50        if timer.tick(time.delta()).just_finished() {
51            info!("Entity timer just finished");
52        }
53    }
54}
55
56/// This system controls ticking the timer within the countdown resource and
57/// handling its state.
58fn countdown(time: Res<Time>, mut countdown: ResMut<Countdown>) {
59    countdown.main_timer.tick(time.delta());
60
61    // The API encourages this kind of timer state checking (if you're only checking for one value)
62    // Additionally, `is_finished()` would accomplish the same thing as `just_finished` due to the
63    // timer being repeating, however this makes more sense visually.
64    if countdown.percent_trigger.tick(time.delta()).just_finished() {
65        if !countdown.main_timer.is_finished() {
66            // Print the percent complete the main timer is.
67            info!(
68                "Timer is {:0.0}% complete!",
69                countdown.main_timer.fraction() * 100.0
70            );
71        } else {
72            // The timer has finished so we pause the percent output timer
73            countdown.percent_trigger.pause();
74            info!("Paused percent trigger timer");
75        }
76    }
77}
Source

pub fn delta_secs(&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 70)
68fn rotate_things(mut q: Query<&mut Transform, With<Rotate>>, time: Res<Time>) {
69    for mut t in &mut q {
70        t.rotate_y(time.delta_secs());
71    }
72}
More examples
Hide additional examples
examples/3d/3d_shapes.rs (line 227)
225fn rotate(mut query: Query<&mut Transform, With<Shape>>, time: Res<Time>) {
226    for mut transform in &mut query {
227        transform.rotate_y(time.delta_secs() / 2.);
228    }
229}
examples/picking/mesh_picking.rs (line 188)
186fn rotate(mut query: Query<&mut Transform, With<Shape>>, time: Res<Time>) {
187    for mut transform in &mut query {
188        transform.rotate_y(time.delta_secs() / 2.);
189    }
190}
examples/2d/2d_shapes.rs (line 217)
215fn rotate(mut query: Query<&mut Transform, With<Mesh2d>>, time: Res<Time>) {
216    for mut transform in &mut query {
217        transform.rotate_z(time.delta_secs() / 2.0);
218    }
219}
examples/asset/compressed_image_saver.rs (line 102)
100fn rotate(mut query: Query<&mut Transform, With<Rotating>>, time: Res<Time>) {
101    for mut transform in &mut query {
102        transform.rotate_y(time.delta_secs() * 0.5);
103    }
104}
examples/gizmos/light_gizmos.rs (line 151)
150fn rotate_camera(mut transform: Single<&mut Transform, With<Camera>>, time: Res<Time>) {
151    transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(time.delta_secs() / 2.));
152}
153
154fn update_config(
155    mut config_store: ResMut<GizmoConfigStore>,
156    keyboard: Res<ButtonInput<KeyCode>>,
157    time: Res<Time>,
158    color_text_query: Single<Entity, With<GizmoColorText>>,
159    mut writer: TextUiWriter,
160) {
161    if keyboard.just_pressed(KeyCode::KeyD) {
162        for (_, config, _) in config_store.iter_mut() {
163            config.depth_bias = if config.depth_bias == 0. { -1. } else { 0. };
164        }
165    }
166
167    let (config, light_config) = config_store.config_mut::<LightGizmoConfigGroup>();
168    if keyboard.pressed(KeyCode::ArrowRight) {
169        config.line.width += 5. * time.delta_secs();
170        config.line.width = config.line.width.clamp(0., 50.);
171    }
172    if keyboard.pressed(KeyCode::ArrowLeft) {
173        config.line.width -= 5. * time.delta_secs();
174        config.line.width = config.line.width.clamp(0., 50.);
175    }
176    if keyboard.just_pressed(KeyCode::KeyA) {
177        config.enabled ^= true;
178    }
179    if keyboard.just_pressed(KeyCode::KeyC) {
180        light_config.color = match light_config.color {
181            LightGizmoColor::Manual(_) => LightGizmoColor::Varied,
182            LightGizmoColor::Varied => LightGizmoColor::MatchLightColor,
183            LightGizmoColor::MatchLightColor => LightGizmoColor::ByLightType,
184            LightGizmoColor::ByLightType => LightGizmoColor::Manual(GRAY.into()),
185        };
186        *writer.text(*color_text_query, 1) = gizmo_color_text(light_config);
187    }
188}
Source

pub fn delta_secs_f64(&self) -> f64

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

Examples found in repository?
examples/stress_tests/bevymark_3d.rs (line 319)
299fn mouse_handler(
300    mut commands: Commands,
301    args: Res<Args>,
302    time: Res<Time>,
303    mouse_button_input: Res<ButtonInput<MouseButton>>,
304    cube_resources: ResMut<CubeResources>,
305    mut counter: ResMut<BevyCounter>,
306    mut rng: Local<Option<ChaCha8Rng>>,
307    mut wave: Local<usize>,
308) {
309    if rng.is_none() {
310        *rng = Some(ChaCha8Rng::seed_from_u64(42));
311    }
312    let rng = rng.as_mut().unwrap();
313
314    if mouse_button_input.just_released(MouseButton::Left) {
315        counter.color = Color::linear_rgb(rng.random(), rng.random(), rng.random());
316    }
317
318    if mouse_button_input.pressed(MouseButton::Left) {
319        let spawn_count = (CUBES_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
320        spawn_cubes(
321            &mut commands,
322            args.into_inner(),
323            &mut counter,
324            spawn_count,
325            cube_resources.into_inner(),
326            None,
327            *wave,
328        );
329        *wave += 1;
330    }
331}
More examples
Hide additional examples
examples/stress_tests/bevymark.rs (line 348)
321fn mouse_handler(
322    mut commands: Commands,
323    args: Res<Args>,
324    time: Res<Time>,
325    mouse_button_input: Res<ButtonInput<MouseButton>>,
326    window: Query<&Window>,
327    bird_resources: ResMut<BirdResources>,
328    mut counter: ResMut<BevyCounter>,
329    mut rng: Local<Option<ChaCha8Rng>>,
330    mut wave: Local<usize>,
331) {
332    let Ok(window) = window.single() else {
333        return;
334    };
335
336    if rng.is_none() {
337        // We're seeding the PRNG here to make this example deterministic for testing purposes.
338        // This isn't strictly required in practical use unless you need your app to be deterministic.
339        *rng = Some(ChaCha8Rng::seed_from_u64(500));
340    }
341    let rng = rng.as_mut().unwrap();
342
343    if mouse_button_input.just_released(MouseButton::Left) {
344        counter.color = Color::linear_rgb(rng.random(), rng.random(), rng.random());
345    }
346
347    if mouse_button_input.pressed(MouseButton::Left) {
348        let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
349        spawn_birds(
350            &mut commands,
351            args.into_inner(),
352            &window.resolution,
353            &mut counter,
354            spawn_count,
355            bird_resources.into_inner(),
356            None,
357            *wave,
358        );
359        *wave += 1;
360    }
361}
examples/ui/text/text_debug.rs (line 275)
248fn change_text_system(
249    mut fps_history: Local<VecDeque<f64>>,
250    mut time_history: Local<VecDeque<Duration>>,
251    time: Res<Time>,
252    diagnostics: Res<DiagnosticsStore>,
253    query: Query<Entity, With<TextChanges>>,
254    mut writer: TextUiWriter,
255) {
256    time_history.push_front(time.elapsed());
257    time_history.truncate(120);
258    let avg_fps = (time_history.len() as f64)
259        / (time_history.front().copied().unwrap_or_default()
260            - time_history.back().copied().unwrap_or_default())
261        .as_secs_f64()
262        .max(0.0001);
263    fps_history.push_front(avg_fps);
264    fps_history.truncate(120);
265    let fps_variance = std_deviation(fps_history.make_contiguous()).unwrap_or_default();
266
267    for entity in &query {
268        let mut fps = 0.0;
269        if let Some(fps_diagnostic) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS)
270            && let Some(fps_smoothed) = fps_diagnostic.smoothed()
271        {
272            fps = fps_smoothed;
273        }
274
275        let mut frame_time = time.delta_secs_f64();
276        if let Some(frame_time_diagnostic) =
277            diagnostics.get(&FrameTimeDiagnosticsPlugin::FRAME_TIME)
278            && let Some(frame_time_smoothed) = frame_time_diagnostic.smoothed()
279        {
280            frame_time = frame_time_smoothed;
281        }
282
283        *writer.text(entity, 0) =
284            format!("{avg_fps:.1} avg fps, {fps_variance:.1} frametime variance",);
285
286        *writer.text(entity, 1) = format!(
287            "\nThis text changes in the bottom right - {fps:.1} fps, {frame_time:.3} ms/frame",
288        );
289
290        *writer.text(entity, 4) = format!("{fps:.1}");
291
292        *writer.text(entity, 6) = format!("{frame_time:.3}");
293    }
294}
Source

pub fn elapsed(&self) -> Duration

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

Examples found in repository?
examples/window/window_settings.rs (line 129)
126fn change_title(mut window: Single<&mut Window>, time: Res<Time>) {
127    window.title = format!(
128        "Seconds since startup: {}",
129        time.elapsed().as_secs_f32().round()
130    );
131}
More examples
Hide additional examples
examples/time/time.rs (line 91)
87fn print_real_time(time: Res<Time<Real>>) {
88    println!(
89        "PreUpdate: this is real time clock, delta is {:?} and elapsed is {:?}",
90        time.delta(),
91        time.elapsed()
92    );
93}
94
95fn print_fixed_time(time: Res<Time>) {
96    println!(
97        "FixedUpdate: this is generic time clock inside fixed, delta is {:?} and elapsed is {:?}",
98        time.delta(),
99        time.elapsed()
100    );
101}
102
103fn print_time(time: Res<Time>) {
104    println!(
105        "Update: this is generic time clock, delta is {:?} and elapsed is {:?}",
106        time.delta(),
107        time.elapsed()
108    );
109}
examples/scene/world_serialization.rs (line 91)
88    fn from_world(world: &mut World) -> Self {
89        let time = world.resource::<Time>();
90        ComponentB {
91            _time_since_startup: time.elapsed(),
92            value: "Default Value".to_string(),
93        }
94    }
examples/ecs/hierarchy.rs (line 76)
69fn setup_common(
70    commands: &mut Commands,
71    time: &Res<Time>,
72    delta: &mut ResMut<Delta>,
73    title: &str,
74    stage: Showcase,
75) {
76    delta.0 = time.elapsed();
77    commands.spawn((
78        Text::new(title),
79        TextFont::from_font_size(36.),
80        DespawnOnExit(stage),
81    ));
82}
examples/ui/text/text_debug.rs (line 256)
248fn change_text_system(
249    mut fps_history: Local<VecDeque<f64>>,
250    mut time_history: Local<VecDeque<Duration>>,
251    time: Res<Time>,
252    diagnostics: Res<DiagnosticsStore>,
253    query: Query<Entity, With<TextChanges>>,
254    mut writer: TextUiWriter,
255) {
256    time_history.push_front(time.elapsed());
257    time_history.truncate(120);
258    let avg_fps = (time_history.len() as f64)
259        / (time_history.front().copied().unwrap_or_default()
260            - time_history.back().copied().unwrap_or_default())
261        .as_secs_f64()
262        .max(0.0001);
263    fps_history.push_front(avg_fps);
264    fps_history.truncate(120);
265    let fps_variance = std_deviation(fps_history.make_contiguous()).unwrap_or_default();
266
267    for entity in &query {
268        let mut fps = 0.0;
269        if let Some(fps_diagnostic) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS)
270            && let Some(fps_smoothed) = fps_diagnostic.smoothed()
271        {
272            fps = fps_smoothed;
273        }
274
275        let mut frame_time = time.delta_secs_f64();
276        if let Some(frame_time_diagnostic) =
277            diagnostics.get(&FrameTimeDiagnosticsPlugin::FRAME_TIME)
278            && let Some(frame_time_smoothed) = frame_time_diagnostic.smoothed()
279        {
280            frame_time = frame_time_smoothed;
281        }
282
283        *writer.text(entity, 0) =
284            format!("{avg_fps:.1} avg fps, {fps_variance:.1} frametime variance",);
285
286        *writer.text(entity, 1) = format!(
287            "\nThis text changes in the bottom right - {fps:.1} fps, {frame_time:.3} ms/frame",
288        );
289
290        *writer.text(entity, 4) = format!("{fps:.1}");
291
292        *writer.text(entity, 6) = format!("{frame_time:.3}");
293    }
294}
Source

pub fn elapsed_secs(&self) -> f32

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

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

Examples found in repository?
examples/ecs/extraction.rs (line 76)
75fn setup(mut commands: Commands, time: Res<Time>) {
76    commands.spawn(A(time.elapsed_secs()));
77    commands.spawn(B(time.elapsed_secs()));
78    commands.spawn(C(time.elapsed_secs()));
79}
80
81// Sets the elapsed time on each of the components on the Main World. Runs each frame.
82fn set_time(mut a: Single<&mut A>, mut b: Single<&mut B>, mut c: Single<&mut C>, time: Res<Time>) {
83    a.0 = time.elapsed_secs();
84    b.0 = time.elapsed_secs();
85    c.0 = time.elapsed_secs();
86}
More examples
Hide additional examples
examples/remote/server.rs (line 81)
79fn move_cube(mut query: Query<&mut Transform, With<Cube>>, time: Res<Time>) {
80    for mut transform in &mut query {
81        transform.translation.y = -cos(time.elapsed_secs()) + 1.5;
82    }
83}
examples/3d/meshlet.rs (line 124)
122fn bunny_wiggler(mut bunny: Query<&mut Transform, With<BunnyWiggler>>, time: Res<Time>) {
123    bunny.single_mut().as_deref_mut().unwrap().translation.z +=
124        ops::cos(time.elapsed_secs() * 10.0) * 0.003;
125}
examples/ui/scroll_and_overflow/overflow_transform.rs (line 113)
111fn rotate_nodes(time: Res<Time>, mut query: Query<(&RotatingClipLayer, &mut UiTransform)>) {
112    for (layer, mut transform) in &mut query {
113        transform.rotation = Rot2::radians(layer.base_rotation + time.elapsed_secs() * layer.speed);
114    }
115}
116
117fn rotating_node(size: f32, rotation: f32, speed: f32, color: Color) -> impl Bundle {
118    (
119        Node {
120            width: px(size),
121            height: px(size),
122            overflow: Overflow::clip(),
123            align_items: AlignItems::Center,
124            justify_content: JustifyContent::Center,
125            border: UiRect::all(px(4)),
126            ..default()
127        },
128        BackgroundColor(color),
129        BorderColor::all(Color::WHITE.with_alpha(0.7)),
130        UiTransform::from_rotation(Rot2::radians(rotation)),
131        RotatingClipLayer {
132            base_rotation: rotation,
133            speed,
134        },
135    )
136}
137
138#[derive(Component)]
139struct InnerNode;
140
141fn scale_inner(time: Res<Time>, mut query: Query<&mut UiTransform, With<InnerNode>>) {
142    for mut transform in query.iter_mut() {
143        transform.scale = Vec2::splat(1. + 0.75 * sin(0.4 * time.elapsed_secs()));
144    }
145}
examples/shader/extended_material_bindless.rs (line 152)
149fn rotate_sphere(mut meshes: Query<&mut Transform, With<Mesh3d>>, time: Res<Time>) {
150    for mut transform in &mut meshes {
151        transform.rotation =
152            Quat::from_euler(EulerRot::YXZ, -time.elapsed_secs(), FRAC_PI_2 * 3.0, 0.0);
153    }
154}
examples/ecs/fixed_timestep.rs (line 21)
17fn frame_update(mut last_time: Local<f32>, time: Res<Time>) {
18    // Default `Time` is `Time<Virtual>` here
19    info!(
20        "time since last frame_update: {}",
21        time.elapsed_secs() - *last_time
22    );
23    *last_time = time.elapsed_secs();
24}
25
26fn fixed_update(mut last_time: Local<f32>, time: Res<Time>, fixed_time: Res<Time<Fixed>>) {
27    // Default `Time`is `Time<Fixed>` here
28    info!(
29        "time since last fixed_update: {}\n",
30        time.elapsed_secs() - *last_time
31    );
32
33    info!("fixed timestep: {}\n", time.delta_secs());
34    // If we want to see the overstep, we need to access `Time<Fixed>` specifically
35    info!(
36        "time accrued toward next fixed_update: {}\n",
37        fixed_time.overstep().as_secs_f32()
38    );
39    *last_time = time.elapsed_secs();
40}
Source

pub fn elapsed_secs_f64(&self) -> f64

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

Source

pub fn elapsed_wrapped(&self) -> Duration

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

Source

pub fn elapsed_secs_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_secs.

Source

pub fn elapsed_secs_wrapped_f64(&self) -> f64

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

Source

pub fn context(&self) -> &T

Returns a reference to the context of this specific clock.

Source

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

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

Source

pub fn as_generic(&self) -> Time

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

Source§

impl Time<Virtual>

Source

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 114)
111fn main() {
112    App::new()
113        .add_plugins(MinimalPlugins)
114        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
115        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
116        .add_systems(PreUpdate, print_real_time)
117        .add_systems(FixedUpdate, print_fixed_time)
118        .add_systems(Update, print_time)
119        .set_runner(runner)
120        .run();
121}
Source

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.

Source

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.

Source

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 158)
157fn 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
167fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
168    time.toggle();
169}
170
171/// Update the `Real` time info text
172fn 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
183fn 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}
Source

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.

Source

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. Otherwise returns the multiplier actually applied to the raw_delta this update. This will usually equal relative_speed(), but if the delta was clamped by max_delta(), it will be less than relative_speed().

Source

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. Otherwise returns the multiplier actually applied to the raw_delta this update. This will usually equal relative_speed(), but if the delta was clamped by max_delta(), it will be less than relative_speed().

Source

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 52)
35fn runner(mut app: App) -> AppExit {
36    banner();
37    help();
38    let stdin = io::stdin();
39    for line in stdin.lock().lines() {
40        if let Err(err) = line {
41            println!("read err: {err:#}");
42            break;
43        }
44        match line.unwrap().as_str() {
45            "" => {
46                app.update();
47            }
48            "f" => {
49                println!("FAST: setting relative speed to 2x");
50                app.world_mut()
51                    .resource_mut::<Time<Virtual>>()
52                    .set_relative_speed(2.0);
53            }
54            "n" => {
55                println!("NORMAL: setting relative speed to 1x");
56                app.world_mut()
57                    .resource_mut::<Time<Virtual>>()
58                    .set_relative_speed(1.0);
59            }
60            "s" => {
61                println!("SLOW: setting relative speed to 0.5x");
62                app.world_mut()
63                    .resource_mut::<Time<Virtual>>()
64                    .set_relative_speed(0.5);
65            }
66            "p" => {
67                println!("PAUSE: pausing virtual clock");
68                app.world_mut().resource_mut::<Time<Virtual>>().pause();
69            }
70            "u" => {
71                println!("UNPAUSE: resuming virtual clock");
72                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
73            }
74            "q" => {
75                println!("QUITTING!");
76                break;
77            }
78            _ => {
79                help();
80            }
81        }
82    }
83
84    AppExit::Success
85}
More examples
Hide additional examples
examples/time/virtual_time.rs (line 46)
43fn 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
122fn 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
136fn 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
152fn get_sprite_translation_x(elapsed: f32) -> f32 {
153    ops::sin(elapsed) * 500.
154}
155
156/// Update the speed of `Time<Virtual>.` by `DELTA`
157fn 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}
Source

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.

Source

pub fn toggle(&mut self)

Stops the clock if it is running, otherwise resumes the clock.

Examples found in repository?
examples/time/virtual_time.rs (line 168)
167fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
168    time.toggle();
169}
More examples
Hide additional examples
examples/3d/solari.rs (line 488)
486fn pause_scene(mut time: ResMut<Time<Virtual>>, key_input: Res<ButtonInput<KeyCode>>) {
487    if key_input.just_pressed(KeyCode::Space) {
488        time.toggle();
489    }
490}
examples/gizmos/2d_gizmos.rs (line 224)
136fn update_config(
137    mut config_store: ResMut<GizmoConfigStore>,
138    keyboard: Res<ButtonInput<KeyCode>>,
139    real_time: Res<Time<Real>>,
140    mut virtual_time: ResMut<Time<Virtual>>,
141) {
142    let (config, _) = config_store.config_mut::<DefaultGizmoConfigGroup>();
143    if keyboard.pressed(KeyCode::ArrowRight) {
144        config.line.width += 5. * real_time.delta_secs();
145        config.line.width = config.line.width.clamp(0., 50.);
146    }
147    if keyboard.pressed(KeyCode::ArrowLeft) {
148        config.line.width -= 5. * real_time.delta_secs();
149        config.line.width = config.line.width.clamp(0., 50.);
150    }
151    if keyboard.just_pressed(KeyCode::Digit1) {
152        config.enabled ^= true;
153    }
154    if keyboard.just_pressed(KeyCode::KeyU) {
155        config.line.style = match config.line.style {
156            GizmoLineStyle::Solid => GizmoLineStyle::Dotted,
157            GizmoLineStyle::Dotted => GizmoLineStyle::Dashed {
158                gap_scale: 3.0,
159                line_scale: 5.0,
160            },
161            _ => GizmoLineStyle::Solid,
162        };
163    }
164    if keyboard.just_pressed(KeyCode::KeyI) {
165        config.line.style = match config.line.style {
166            GizmoLineStyle::Solid => GizmoLineStyle::Dashed {
167                gap_scale: 3.0,
168                line_scale: 5.0,
169            },
170            GizmoLineStyle::Dotted => GizmoLineStyle::Solid,
171            _ => GizmoLineStyle::Dotted,
172        };
173    }
174    if keyboard.just_pressed(KeyCode::KeyJ) {
175        config.line.joints = match config.line.joints {
176            GizmoLineJoint::Bevel => GizmoLineJoint::Miter,
177            GizmoLineJoint::Miter => GizmoLineJoint::Round(4),
178            GizmoLineJoint::Round(_) => GizmoLineJoint::None,
179            GizmoLineJoint::None => GizmoLineJoint::Bevel,
180        };
181    }
182
183    if keyboard.just_pressed(KeyCode::KeyK) {
184        config.line.joints = match config.line.joints {
185            GizmoLineJoint::Bevel => GizmoLineJoint::None,
186            GizmoLineJoint::Miter => GizmoLineJoint::Bevel,
187            GizmoLineJoint::Round(_) => GizmoLineJoint::Miter,
188            GizmoLineJoint::None => GizmoLineJoint::Round(4),
189        };
190    }
191
192    let (my_config, _) = config_store.config_mut::<MyRoundGizmos>();
193    if keyboard.pressed(KeyCode::ArrowUp) {
194        my_config.line.width += 5. * real_time.delta_secs();
195        my_config.line.width = my_config.line.width.clamp(0., 50.);
196    }
197    if keyboard.pressed(KeyCode::ArrowDown) {
198        my_config.line.width -= 5. * real_time.delta_secs();
199        my_config.line.width = my_config.line.width.clamp(0., 50.);
200    }
201    if keyboard.just_pressed(KeyCode::Digit2) {
202        my_config.enabled ^= true;
203    }
204    if keyboard.just_pressed(KeyCode::KeyI) {
205        my_config.line.style = match my_config.line.style {
206            GizmoLineStyle::Solid => GizmoLineStyle::Dotted,
207            GizmoLineStyle::Dotted => GizmoLineStyle::Dashed {
208                gap_scale: 3.0,
209                line_scale: 5.0,
210            },
211            _ => GizmoLineStyle::Solid,
212        };
213    }
214    if keyboard.just_pressed(KeyCode::KeyK) {
215        my_config.line.joints = match my_config.line.joints {
216            GizmoLineJoint::Bevel => GizmoLineJoint::Miter,
217            GizmoLineJoint::Miter => GizmoLineJoint::Round(4),
218            GizmoLineJoint::Round(_) => GizmoLineJoint::None,
219            GizmoLineJoint::None => GizmoLineJoint::Bevel,
220        };
221    }
222
223    if keyboard.just_pressed(KeyCode::Space) {
224        virtual_time.toggle();
225    }
226}
examples/gizmos/3d_gizmos.rs (line 319)
231fn update_config(
232    mut config_store: ResMut<GizmoConfigStore>,
233    keyboard: Res<ButtonInput<KeyCode>>,
234    real_time: Res<Time<Real>>,
235    mut virtual_time: ResMut<Time<Virtual>>,
236) {
237    if keyboard.just_pressed(KeyCode::KeyT) {
238        for (_, config, _) in config_store.iter_mut() {
239            config.depth_bias = if config.depth_bias == 0. { -1. } else { 0. };
240        }
241    }
242    if keyboard.just_pressed(KeyCode::KeyP) {
243        for (_, config, _) in config_store.iter_mut() {
244            // Toggle line perspective
245            config.line.perspective ^= true;
246            // Increase the line width when line perspective is on
247            config.line.width *= if config.line.perspective { 5. } else { 1. / 5. };
248        }
249    }
250
251    let (config, _) = config_store.config_mut::<DefaultGizmoConfigGroup>();
252    if keyboard.pressed(KeyCode::ArrowRight) {
253        config.line.width += 5. * real_time.delta_secs();
254        config.line.width = config.line.width.clamp(0., 50.);
255    }
256    if keyboard.pressed(KeyCode::ArrowLeft) {
257        config.line.width -= 5. * real_time.delta_secs();
258        config.line.width = config.line.width.clamp(0., 50.);
259    }
260    if keyboard.just_pressed(KeyCode::Digit1) {
261        config.enabled ^= true;
262    }
263    if keyboard.just_pressed(KeyCode::KeyU) {
264        config.line.style = match config.line.style {
265            GizmoLineStyle::Solid => GizmoLineStyle::Dotted,
266            GizmoLineStyle::Dotted => GizmoLineStyle::Dashed {
267                gap_scale: 3.0,
268                line_scale: 5.0,
269            },
270            _ => GizmoLineStyle::Solid,
271        };
272    }
273    if keyboard.just_pressed(KeyCode::KeyJ) {
274        config.line.joints = match config.line.joints {
275            GizmoLineJoint::Bevel => GizmoLineJoint::Miter,
276            GizmoLineJoint::Miter => GizmoLineJoint::Round(4),
277            GizmoLineJoint::Round(_) => GizmoLineJoint::None,
278            GizmoLineJoint::None => GizmoLineJoint::Bevel,
279        };
280    }
281
282    let (my_config, _) = config_store.config_mut::<MyRoundGizmos>();
283    if keyboard.pressed(KeyCode::ArrowUp) {
284        my_config.line.width += 5. * real_time.delta_secs();
285        my_config.line.width = my_config.line.width.clamp(0., 50.);
286    }
287    if keyboard.pressed(KeyCode::ArrowDown) {
288        my_config.line.width -= 5. * real_time.delta_secs();
289        my_config.line.width = my_config.line.width.clamp(0., 50.);
290    }
291    if keyboard.just_pressed(KeyCode::Digit2) {
292        my_config.enabled ^= true;
293    }
294    if keyboard.just_pressed(KeyCode::KeyI) {
295        my_config.line.style = match my_config.line.style {
296            GizmoLineStyle::Solid => GizmoLineStyle::Dotted,
297            GizmoLineStyle::Dotted => GizmoLineStyle::Dashed {
298                gap_scale: 3.0,
299                line_scale: 5.0,
300            },
301            _ => GizmoLineStyle::Solid,
302        };
303    }
304    if keyboard.just_pressed(KeyCode::KeyK) {
305        my_config.line.joints = match my_config.line.joints {
306            GizmoLineJoint::Bevel => GizmoLineJoint::Miter,
307            GizmoLineJoint::Miter => GizmoLineJoint::Round(4),
308            GizmoLineJoint::Round(_) => GizmoLineJoint::None,
309            GizmoLineJoint::None => GizmoLineJoint::Bevel,
310        };
311    }
312
313    if keyboard.just_pressed(KeyCode::KeyB) {
314        // AABB gizmos are normally only drawn on entities with a ShowAabbGizmo component
315        // We can change this behavior in the configuration of AabbGizmoGroup
316        config_store.config_mut::<AabbGizmoConfigGroup>().1.draw_all ^= true;
317    }
318    if keyboard.just_pressed(KeyCode::Space) {
319        virtual_time.toggle();
320    }
321}
Source

pub fn pause(&mut self)

Stops the clock, preventing it from advancing until resumed.

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

pub fn unpause(&mut self)

Resumes the clock.

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

pub fn is_paused(&self) -> bool

Returns true if the clock is currently paused.

Examples found in repository?
examples/3d/solari.rs (line 587)
568fn update_control_text(
569    mut text: Single<&mut Text, With<ControlText>>,
570    solari_lighting: Single<&SolariLighting>,
571    robot_light_material: Option<Res<RobotLightMaterial>>,
572    materials: Res<Assets<StandardMaterial>>,
573    directional_light: Query<Entity, With<DirectionalLight>>,
574    time: Res<Time<Virtual>>,
575    args: Res<Args>,
576    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_rr_supported: Option<
577        Res<DlssRayReconstructionSupported>,
578    >,
579    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_camera: Query<
580        Has<Dlss<DlssRayReconstructionFeature>>,
581        With<SolariLighting>,
582    >,
583) {
584    text.0.clear();
585
586    if args.many_lights != Some(true) {
587        if time.is_paused() {
588            text.0.push_str("(Space): Resume");
589        } else {
590            text.0.push_str("(Space): Pause");
591        }
592
593        if directional_light.single().is_ok() {
594            text.0.push_str("\n(1): Disable directional light");
595        } else {
596            text.0.push_str("\n(1): Enable directional light");
597        }
598
599        match robot_light_material.and_then(|m| materials.get(&m.0)) {
600            Some(robot_light_material) if robot_light_material.emissive != LinearRgba::BLACK => {
601                text.0.push_str("\n(2): Disable robot emissive light");
602            }
603            _ => {
604                text.0.push_str("\n(2): Enable robot emissive light");
605            }
606        }
607    }
608
609    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
610    if dlss_rr_supported.is_some() {
611        if matches!(dlss_camera.single(), Ok(true)) {
612            text.0.push_str("\n(3): Disable DLSS Ray Reconstruction");
613        } else {
614            text.0.push_str("\n(3): Enable DLSS Ray Reconstruction");
615        }
616    } else {
617        text.0
618            .push_str("\nDenoising: DLSS Ray Reconstruction not supported");
619    }
620
621    #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
622    text.0
623        .push_str("\nDenoising: App not compiled with DLSS support");
624
625    if solari_lighting.restir {
626        text.0.push_str("\n(R): Disable ReSTIR");
627    } else {
628        text.0.push_str("\n(R): Enable ReSTIR");
629    }
630}
Source

pub fn was_paused(&self) -> bool

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

Trait Implementations§

Source§

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

Source§

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

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

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

Source§

const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::SparseSet

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Time<T>>>

Returns ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_discard ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
Source§

const HAS_SUMMARY_TICK: bool = false

Set this constant to true if the component should track a summary tick. Read more
Source§

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

Source§

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

Source§

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

Formats the value using the given formatter. Read more
Source§

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

Source§

fn default() -> Time<T>

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

impl<T> FromArg for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync,

Source§

type This<'from_arg> = Time<T>

The type to convert into. Read more
Source§

fn from_arg(arg: Arg<'_>) -> Result<<Time<T> as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

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

Source§

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

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

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

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

impl<T> GetOwnership for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

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

Source§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
Source§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
Source§

impl<T> IntoReturn for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync,

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where Time<T>: 'into_return,

Converts Self into a Return value.
Source§

impl<T> PartialReflect for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync,

Source§

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

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

fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
Source§

fn reflect_kind(&self) -> ReflectKind

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

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

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

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

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

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

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

fn try_into_reflect( self: Box<Time<T>>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>

Attempts to cast this type to a boxed, fully-reflected value.
Source§

fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>

Attempts to cast this type to a fully-reflected value.
Source§

fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>

Attempts to cast this type to a mutable, fully-reflected value.
Source§

fn into_partial_reflect(self: Box<Time<T>>) -> Box<dyn PartialReflect>

Casts this type to a boxed, reflected value. Read more
Source§

fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)

Casts this type to a reflected value. Read more
Source§

fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)

Casts this type to a mutable, reflected value. Read more
Source§

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

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

fn reflect_partial_cmp( &self, value: &(dyn PartialReflect + 'static), ) -> Option<Ordering>

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

fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>

Attempts to clone Self using reflection. Read more
Source§

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

Applies a reflected value to this value. Read more
Source§

fn to_dynamic(&self) -> Result<Box<dyn PartialReflect>, ReflectCloneError>

Converts this reflected value into its dynamic representation based on its kind. Read more
Source§

fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
where T: 'static, Self: Sized + TypePath,

For a type implementing PartialReflect, combines reflect_clone and take in a useful fashion, automatically constructing an appropriate ReflectCloneError if the downcast fails.
Source§

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

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

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

Debug formatter for the value. Read more
Source§

fn is_dynamic(&self) -> bool

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

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

Source§

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

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

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

Returns the value as a &dyn Any. Read more
Source§

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

Returns the value as a &mut dyn Any. Read more
Source§

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

Casts this type to a boxed, fully-reflected value.
Source§

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

Casts this type to a fully-reflected value.
Source§

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

Casts this type to a mutable, fully-reflected value.
Source§

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
Source§

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

Source§

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

Source§

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

Gets a reference to the value of the field named name as a &dyn PartialReflect.
Source§

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

Gets a mutable reference to the value of the field named name as a &mut dyn PartialReflect.
Source§

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

Gets a reference to the value of the field with index index as a &dyn PartialReflect.
Source§

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

Gets a mutable reference to the value of the field with index index as a &mut dyn PartialReflect.
Source§

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

Gets the name of the field with index index.
Source§

fn index_of_name(&self, name: &str) -> Option<usize>

Gets the index of the field with the given name.
Source§

fn field_len(&self) -> usize

Returns the number of fields in the struct.
Source§

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

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

fn to_dynamic_struct(&self) -> Result<DynamicStruct, ReflectCloneError>

Creates a new DynamicStruct from this struct. Read more
Source§

fn get_represented_struct_info(&self) -> Option<&'static StructInfo>

Will return None if TypeInfo is not available.
Source§

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

Source§

fn type_path() -> &'static str

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

fn short_type_path() -> &'static str

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

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

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

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

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

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

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

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

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.

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> UnsafeUnpin for Time<T>
where T: UnsafeUnpin,

§

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
Source§

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

Source§

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
Source§

impl<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>

Source§

fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>

Returns an iterator over this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>, C: Sized,

Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

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

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

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

Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

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

Source§

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

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

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

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

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

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

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

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

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

Source§

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.
Source§

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.
Source§

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.
Source§

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.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

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

Source§

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.
Source§

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

Source§

impl<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

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

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> ErasedBundleTemplate for T
where T: Template + Send + Sync + 'static, <T as Template>::Output: Bundle,

Source§

unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, ) -> Result<(), BevyError>

Applies this template to the given entity. Read more
Source§

fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>

Clones this template. See Clone.
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> ErasedTemplate for T
where T: Template + Send + Sync + 'static, <T as Template>::Output: SceneEffect,

Source§

unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, ) -> Result<(), BevyError>

Applies this template to the given entity. Read more
Source§

fn clone_template(&self) -> Box<dyn ErasedTemplate>

Clones this template. See Clone.
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromTemplate for T
where T: Clone + Default + Unpin,

Source§

type Template = T

The Template for this type.
Source§

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

Source§

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

Creates Self using default().

Source§

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

Source§

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

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

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

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

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

Source§

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

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

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

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

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
Source§

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
Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> HitDataExtra for T
where T: Send + Sync + Debug + Any + 'static,

Source§

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

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

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

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

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.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

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

Source§

fn into_sample(self) -> T

Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

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

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

impl<G> PatchFromTemplate for G
where G: FromTemplate,

Source§

type Template = <G as FromTemplate>::Template

The Template that will be patched.
Source§

fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
where F: FnOnce(&mut <G as PatchFromTemplate>::Template, &mut ResolveContext<'_>),

Takes a “patch function” func, and turns it into a TemplatePatch.
Source§

impl<T> PatchTemplate for T
where T: Template,

Source§

fn patch_template<F>(func: F) -> TemplatePatch<F, T>
where F: FnOnce(&mut T, &mut ResolveContext<'_>),

Takes a “patch function” func that patches this Template, and turns it into a TemplatePatch.
Source§

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

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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> Reflectable for T

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<C> SceneEffect for C
where C: Component,

Source§

fn apply( self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, )

Applies the scene effect to the current context.
Source§

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

Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> Template for T
where T: Clone + Unpin,

Source§

type Output = T

The type of value produced by this Template.
Source§

fn build_template( &self, _context: &mut TemplateContext<'_, '_>, ) -> Result<<T as Template>::Output, BevyError>

Uses this template and the given entity context to produce a Template::Output.
Source§

fn clone_template(&self) -> T

Clones this template. See Clone.
Source§

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

Source§

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
Source§

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

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

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

Source§

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.
Source§

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

Source§

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

Creates a type-erased clone of self.
Source§

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

Source§

fn vzip(self) -> V

Source§

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

Source§

impl<T> WasmNotSendSync for T

Source§

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

Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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