Struct bevy::prelude::Timer

source ·
pub struct Timer { /* private fields */ }
Expand description

Tracks elapsed time. Enters the finished state once duration is reached.

Non repeating timers will stop tracking and stay in the finished state until reset. Repeating timers will only be in the finished state on each tick duration is reached or exceeded, and can still be reset at any given point.

Paused timers will not have elapsed time increased.

Implementations§

source§

impl Timer

source

pub fn new(duration: Duration, mode: TimerMode) -> Timer

Creates a new timer with a given duration.

See also Timer::from_seconds.

Examples found in repository?
examples/app/plugin.rs (line 34)
31
32
33
34
35
36
37
38
    fn build(&self, app: &mut App) {
        let state = PrintMessageState {
            message: self.message.clone(),
            timer: Timer::new(self.wait_duration, TimerMode::Repeating),
        };
        app.insert_resource(state)
            .add_systems(Update, print_message_system);
    }
More examples
Hide additional examples
examples/ui/ui_scaling.rs (line 17)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .insert_resource(TextSettings {
            allow_dynamic_font_size: true,
            ..default()
        })
        .insert_resource(TargetScale {
            start_scale: 1.0,
            target_scale: 1.0,
            target_time: Timer::new(Duration::from_millis(SCALE_TIME), TimerMode::Once),
        })
        .add_systems(Startup, setup)
        .add_systems(
            Update,
            (change_scaling, apply_scaling.after(change_scaling)),
        )
        .run();
}
source

pub fn from_seconds(duration: f32, mode: TimerMode) -> Timer

Creates a new timer with a given duration in seconds.

§Example
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
Examples found in repository?
examples/stress_tests/many_cubes.rs (line 315)
314
315
316
    fn default() -> Self {
        Self(Timer::from_seconds(1.0, TimerMode::Repeating))
    }
More examples
Hide additional examples
examples/stress_tests/many_lights.rs (line 185)
184
185
186
    fn default() -> Self {
        Self(Timer::from_seconds(1.0, TimerMode::Repeating))
    }
examples/stress_tests/many_sprites.rs (line 119)
118
119
120
    fn default() -> Self {
        Self(Timer::from_seconds(1.0, TimerMode::Repeating))
    }
examples/ecs/event.rs (line 32)
30
31
32
33
34
    fn default() -> Self {
        EventTriggerState {
            event_timer: Timer::from_seconds(1.0, TimerMode::Repeating),
        }
    }
examples/games/contributors.rs (line 49)
47
48
49
50
51
52
    fn default() -> Self {
        Self {
            timer: Timer::from_seconds(SHOWCASE_TIMER_SECS, TimerMode::Repeating),
            has_triggered: false,
        }
    }
examples/ui/font_atlas_debug.rs (line 28)
24
25
26
27
28
29
30
    fn default() -> Self {
        Self {
            atlas_count: 0,
            handle: Handle::default(),
            timer: Timer::from_seconds(0.05, TimerMode::Repeating),
        }
    }
source

pub fn finished(&self) -> bool

Returns true if the timer has reached its duration.

For repeating timers, this method behaves identically to Timer::just_finished.

§Examples
use std::time::Duration;

let mut timer_once = Timer::from_seconds(1.0, TimerMode::Once);
timer_once.tick(Duration::from_secs_f32(1.5));
assert!(timer_once.finished());
timer_once.tick(Duration::from_secs_f32(0.5));
assert!(timer_once.finished());

let mut timer_repeating = Timer::from_seconds(1.0, TimerMode::Repeating);
timer_repeating.tick(Duration::from_secs_f32(1.1));
assert!(timer_repeating.finished());
timer_repeating.tick(Duration::from_secs_f32(0.8));
assert!(!timer_repeating.finished());
timer_repeating.tick(Duration::from_secs_f32(0.6));
assert!(timer_repeating.finished());
Examples found in repository?
examples/ui/ui_scaling.rs (line 126)
125
126
127
    fn already_completed(&self) -> bool {
        self.target_time.finished() && !self.target_time.just_finished()
    }
More examples
Hide additional examples
examples/app/plugin.rs (line 48)
47
48
49
50
51
fn print_message_system(mut state: ResMut<PrintMessageState>, time: Res<Time>) {
    if state.timer.tick(time.delta()).finished() {
        info!("{}", state.message);
    }
}
examples/games/game_menu.rs (line 111)
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    fn countdown(
        mut game_state: ResMut<NextState<GameState>>,
        time: Res<Time>,
        mut timer: ResMut<SplashTimer>,
    ) {
        if timer.tick(time.delta()).finished() {
            game_state.set(GameState::Menu);
        }
    }
}

mod game {
    use bevy::prelude::*;

    use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};

    // This plugin will contain the game. In this case, it's just be a screen that will
    // display the current settings for 5 seconds before returning to the menu
    pub fn game_plugin(app: &mut App) {
        app.add_systems(OnEnter(GameState::Game), game_setup)
            .add_systems(Update, game.run_if(in_state(GameState::Game)))
            .add_systems(OnExit(GameState::Game), despawn_screen::<OnGameScreen>);
    }

    // Tag component used to tag entities added on the game screen
    #[derive(Component)]
    struct OnGameScreen;

    #[derive(Resource, Deref, DerefMut)]
    struct GameTimer(Timer);

    fn game_setup(
        mut commands: Commands,
        display_quality: Res<DisplayQuality>,
        volume: Res<Volume>,
    ) {
        commands
            .spawn((
                NodeBundle {
                    style: Style {
                        width: Val::Percent(100.0),
                        height: Val::Percent(100.0),
                        // center children
                        align_items: AlignItems::Center,
                        justify_content: JustifyContent::Center,
                        ..default()
                    },
                    ..default()
                },
                OnGameScreen,
            ))
            .with_children(|parent| {
                // First create a `NodeBundle` for centering what we want to display
                parent
                    .spawn(NodeBundle {
                        style: Style {
                            // This will display its children in a column, from top to bottom
                            flex_direction: FlexDirection::Column,
                            // `align_items` will align children on the cross axis. Here the main axis is
                            // vertical (column), so the cross axis is horizontal. This will center the
                            // children
                            align_items: AlignItems::Center,
                            ..default()
                        },
                        background_color: Color::BLACK.into(),
                        ..default()
                    })
                    .with_children(|parent| {
                        // Display two lines of text, the second one with the current settings
                        parent.spawn(
                            TextBundle::from_section(
                                "Will be back to the menu shortly...",
                                TextStyle {
                                    font_size: 80.0,
                                    color: TEXT_COLOR,
                                    ..default()
                                },
                            )
                            .with_style(Style {
                                margin: UiRect::all(Val::Px(50.0)),
                                ..default()
                            }),
                        );
                        parent.spawn(
                            TextBundle::from_sections([
                                TextSection::new(
                                    format!("quality: {:?}", *display_quality),
                                    TextStyle {
                                        font_size: 60.0,
                                        color: Color::BLUE,
                                        ..default()
                                    },
                                ),
                                TextSection::new(
                                    " - ",
                                    TextStyle {
                                        font_size: 60.0,
                                        color: TEXT_COLOR,
                                        ..default()
                                    },
                                ),
                                TextSection::new(
                                    format!("volume: {:?}", *volume),
                                    TextStyle {
                                        font_size: 60.0,
                                        color: Color::GREEN,
                                        ..default()
                                    },
                                ),
                            ])
                            .with_style(Style {
                                margin: UiRect::all(Val::Px(50.0)),
                                ..default()
                            }),
                        );
                    });
            });
        // Spawn a 5 seconds timer to trigger going back to the menu
        commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
    }

    // Tick the timer, and change state when finished
    fn game(
        time: Res<Time>,
        mut game_state: ResMut<NextState<GameState>>,
        mut timer: ResMut<GameTimer>,
    ) {
        if timer.tick(time.delta()).finished() {
            game_state.set(GameState::Menu);
        }
    }
examples/ecs/event.rs (line 44)
38
39
40
41
42
43
44
45
46
47
48
49
50
fn event_trigger(
    time: Res<Time>,
    mut state: ResMut<EventTriggerState>,
    mut my_events: EventWriter<MyEvent>,
    mut play_sound_events: EventWriter<PlaySound>,
) {
    if state.event_timer.tick(time.delta()).finished() {
        my_events.send(MyEvent {
            message: "MyEvent just happened!".to_string(),
        });
        play_sound_events.send_default();
    }
}
examples/ui/font_atlas_debug.rs (line 61)
60
61
62
63
64
65
66
67
68
69
70
71
72
fn text_update_system(mut state: ResMut<State>, time: Res<Time>, mut query: Query<&mut Text>) {
    if state.timer.tick(time.delta()).finished() {
        for mut text in &mut query {
            let c = rand::random::<u8>() as char;
            let string = &mut text.sections[0].value;
            if !string.contains(c) {
                string.push(c);
            }
        }

        state.timer.reset();
    }
}
examples/time/timers.rs (line 65)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
fn countdown(time: Res<Time>, mut countdown: ResMut<Countdown>) {
    countdown.main_timer.tick(time.delta());

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

pub fn just_finished(&self) -> bool

Returns true only on the tick the timer reached its duration.

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
timer.tick(Duration::from_secs_f32(1.5));
assert!(timer.just_finished());
timer.tick(Duration::from_secs_f32(0.5));
assert!(!timer.just_finished());
Examples found in repository?
examples/ui/ui_scaling.rs (line 126)
125
126
127
    fn already_completed(&self) -> bool {
        self.target_time.finished() && !self.target_time.just_finished()
    }
More examples
Hide additional examples
examples/stress_tests/many_sprites.rs (line 127)
124
125
126
127
128
129
130
fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) {
    timer.tick(time.delta());

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

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

struct LogVisibleLights;

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

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

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

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

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

    // The API encourages this kind of timer state checking (if you're only checking for one value)
    // Additionally, `finished()` would accomplish the same thing as `just_finished` due to the
    // timer being repeating, however this makes more sense visually.
    if countdown.percent_trigger.tick(time.delta()).just_finished() {
        if !countdown.main_timer.finished() {
            // Print the percent complete the main timer is.
            info!(
                "Timer is {:0.0}% complete!",
                countdown.main_timer.fraction() * 100.0
            );
        } else {
            // The timer has finished so we pause the percent output timer
            countdown.percent_trigger.pause();
            info!("Paused percent trigger timer");
        }
    }
}
examples/stress_tests/many_cubes.rs (line 301)
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
fn print_mesh_count(
    time: Res<Time>,
    mut timer: Local<PrintingTimer>,
    sprites: Query<(&Handle<Mesh>, &ViewVisibility)>,
) {
    timer.tick(time.delta());

    if timer.just_finished() {
        info!(
            "Meshes: {} - Visible Meshes {}",
            sprites.iter().len(),
            sprites.iter().filter(|(_, vis)| vis.get()).count(),
        );
    }
}
source

pub fn elapsed(&self) -> Duration

Returns the time elapsed on the timer. Guaranteed to be between 0.0 and duration. Will only equal duration when the timer is finished and non repeating.

See also Stopwatch::elapsed.

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
timer.tick(Duration::from_secs_f32(0.5));
assert_eq!(timer.elapsed(), Duration::from_secs_f32(0.5));
source

pub fn elapsed_secs(&self) -> f32

Returns the time elapsed on the timer as an f32. See also Timer::elapsed.

source

pub fn set_elapsed(&mut self, time: Duration)

Sets the elapsed time of the timer without any other considerations.

See also Stopwatch::set.

§
use std::time::Duration;
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
timer.set_elapsed(Duration::from_secs(2));
assert_eq!(timer.elapsed(), Duration::from_secs(2));
// the timer is not finished even if the elapsed time is greater than the duration.
assert!(!timer.finished());
Examples found in repository?
examples/stress_tests/many_animated_sprites.rs (line 84)
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
fn setup(
    mut commands: Commands,
    assets: Res<AssetServer>,
    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
) {
    warn!(include_str!("warning_string.txt"));

    let mut rng = rand::thread_rng();

    let tile_size = Vec2::splat(64.0);
    let map_size = Vec2::splat(320.0);

    let half_x = (map_size.x / 2.0) as i32;
    let half_y = (map_size.y / 2.0) as i32;

    let texture_handle = assets.load("textures/rpg/chars/gabe/gabe-idle-run.png");
    let texture_atlas = TextureAtlasLayout::from_grid(Vec2::new(24.0, 24.0), 7, 1, None, None);
    let texture_atlas_handle = texture_atlases.add(texture_atlas);

    // Spawns the camera

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

    // Builds and spawns the sprites
    for y in -half_y..half_y {
        for x in -half_x..half_x {
            let position = Vec2::new(x as f32, y as f32);
            let translation = (position * tile_size).extend(rng.gen::<f32>());
            let rotation = Quat::from_rotation_z(rng.gen::<f32>());
            let scale = Vec3::splat(rng.gen::<f32>() * 2.0);
            let mut timer = Timer::from_seconds(0.1, TimerMode::Repeating);
            timer.set_elapsed(Duration::from_secs_f32(rng.gen::<f32>()));

            commands.spawn((
                SpriteSheetBundle {
                    texture: texture_handle.clone(),
                    atlas: TextureAtlas {
                        layout: texture_atlas_handle.clone(),
                        ..Default::default()
                    },
                    transform: Transform {
                        translation,
                        rotation,
                        scale,
                    },
                    sprite: Sprite {
                        custom_size: Some(tile_size),
                        ..default()
                    },
                    ..default()
                },
                AnimationTimer(timer),
            ));
        }
    }
}
source

pub fn duration(&self) -> Duration

Returns the duration of the timer.

§Examples
use std::time::Duration;
let timer = Timer::new(Duration::from_secs(1), TimerMode::Once);
assert_eq!(timer.duration(), Duration::from_secs(1));
source

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

Sets the duration of the timer.

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(1.5, TimerMode::Once);
timer.set_duration(Duration::from_secs(1));
assert_eq!(timer.duration(), Duration::from_secs(1));
source

pub fn mode(&self) -> TimerMode

Returns the mode of the timer.

§Examples
let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating);
assert_eq!(timer.mode(), TimerMode::Repeating);
source

pub fn set_mode(&mut self, mode: TimerMode)

Sets the mode of the timer.

§Examples
let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating);
timer.set_mode(TimerMode::Once);
assert_eq!(timer.mode(), TimerMode::Once);
source

pub fn tick(&mut self, delta: Duration) -> &Timer

Advance the timer by delta seconds. Non repeating timer will clamp at duration. Repeating timer will wrap around. Will not affect paused timers.

See also Stopwatch::tick.

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
let mut repeating = Timer::from_seconds(1.0, TimerMode::Repeating);
timer.tick(Duration::from_secs_f32(1.5));
repeating.tick(Duration::from_secs_f32(1.5));
assert_eq!(timer.elapsed_secs(), 1.0);
assert_eq!(repeating.elapsed_secs(), 0.5);
Examples found in repository?
examples/ui/ui_scaling.rs (line 121)
120
121
122
123
    fn tick(&mut self, delta: Duration) -> &Self {
        self.target_time.tick(delta);
        self
    }
More examples
Hide additional examples
examples/app/plugin.rs (line 48)
47
48
49
50
51
fn print_message_system(mut state: ResMut<PrintMessageState>, time: Res<Time>) {
    if state.timer.tick(time.delta()).finished() {
        info!("{}", state.message);
    }
}
examples/stress_tests/many_sprites.rs (line 125)
124
125
126
127
128
129
130
fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) {
    timer.tick(time.delta());

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

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

struct LogVisibleLights;

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

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

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

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

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

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

pub fn pause(&mut self)

Pauses the Timer. Disables the ticking of the timer.

See also Stopwatch::pause.

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
timer.pause();
timer.tick(Duration::from_secs_f32(0.5));
assert_eq!(timer.elapsed_secs(), 0.0);
Examples found in repository?
examples/time/timers.rs (line 73)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
fn countdown(time: Res<Time>, mut countdown: ResMut<Countdown>) {
    countdown.main_timer.tick(time.delta());

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

pub fn unpause(&mut self)

Unpauses the Timer. Resumes the ticking of the timer.

See also Stopwatch::unpause().

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
timer.pause();
timer.tick(Duration::from_secs_f32(0.5));
timer.unpause();
timer.tick(Duration::from_secs_f32(0.5));
assert_eq!(timer.elapsed_secs(), 0.5);
source

pub fn paused(&self) -> bool

Returns true if the timer is paused.

See also Stopwatch::paused.

§Examples
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
assert!(!timer.paused());
timer.pause();
assert!(timer.paused());
timer.unpause();
assert!(!timer.paused());
source

pub fn reset(&mut self)

Resets the timer. The reset doesn’t affect the paused state of the timer.

See also Stopwatch::reset.

Examples

use std::time::Duration;
let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
timer.tick(Duration::from_secs_f32(1.5));
timer.reset();
assert!(!timer.finished());
assert!(!timer.just_finished());
assert_eq!(timer.elapsed_secs(), 0.0);
Examples found in repository?
examples/ui/ui_scaling.rs (line 111)
108
109
110
111
112
    fn set_scale(&mut self, scale: f32) {
        self.start_scale = self.current_scale();
        self.target_scale = scale;
        self.target_time.reset();
    }
More examples
Hide additional examples
examples/ui/font_atlas_debug.rs (line 70)
60
61
62
63
64
65
66
67
68
69
70
71
72
fn text_update_system(mut state: ResMut<State>, time: Res<Time>, mut query: Query<&mut Text>) {
    if state.timer.tick(time.delta()).finished() {
        for mut text in &mut query {
            let c = rand::random::<u8>() as char;
            let string = &mut text.sections[0].value;
            if !string.contains(c) {
                string.push(c);
            }
        }

        state.timer.reset();
    }
}
examples/games/alien_cake_addict.rs (line 235)
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
fn move_player(
    mut commands: Commands,
    keyboard_input: Res<ButtonInput<KeyCode>>,
    mut game: ResMut<Game>,
    mut transforms: Query<&mut Transform>,
    time: Res<Time>,
) {
    if game.player.move_cooldown.tick(time.delta()).finished() {
        let mut moved = false;
        let mut rotation = 0.0;

        if keyboard_input.pressed(KeyCode::ArrowUp) {
            if game.player.i < BOARD_SIZE_I - 1 {
                game.player.i += 1;
            }
            rotation = -PI / 2.;
            moved = true;
        }
        if keyboard_input.pressed(KeyCode::ArrowDown) {
            if game.player.i > 0 {
                game.player.i -= 1;
            }
            rotation = PI / 2.;
            moved = true;
        }
        if keyboard_input.pressed(KeyCode::ArrowRight) {
            if game.player.j < BOARD_SIZE_J - 1 {
                game.player.j += 1;
            }
            rotation = PI;
            moved = true;
        }
        if keyboard_input.pressed(KeyCode::ArrowLeft) {
            if game.player.j > 0 {
                game.player.j -= 1;
            }
            rotation = 0.0;
            moved = true;
        }

        // move on the board
        if moved {
            game.player.move_cooldown.reset();
            *transforms.get_mut(game.player.entity.unwrap()).unwrap() = Transform {
                translation: Vec3::new(
                    game.player.i as f32,
                    game.board[game.player.j][game.player.i].height,
                    game.player.j as f32,
                ),
                rotation: Quat::from_rotation_y(rotation),
                ..default()
            };
        }
    }

    // eat the cake!
    if let Some(entity) = game.bonus.entity {
        if game.player.i == game.bonus.i && game.player.j == game.bonus.j {
            game.score += 2;
            game.cake_eaten += 1;
            commands.entity(entity).despawn_recursive();
            game.bonus.entity = None;
        }
    }
}
source

pub fn fraction(&self) -> f32

Returns the fraction of the timer elapsed time (goes from 0.0 to 1.0).

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(2.0, TimerMode::Once);
timer.tick(Duration::from_secs_f32(0.5));
assert_eq!(timer.fraction(), 0.25);
Examples found in repository?
examples/ui/ui_scaling.rs (line 115)
114
115
116
117
118
    fn current_scale(&self) -> f32 {
        let completion = self.target_time.fraction();
        let t = ease_in_expo(completion);
        self.start_scale.lerp(self.target_scale, t)
    }
More examples
Hide additional examples
examples/time/timers.rs (line 69)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
fn countdown(time: Res<Time>, mut countdown: ResMut<Countdown>) {
    countdown.main_timer.tick(time.delta());

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

pub fn fraction_remaining(&self) -> f32

Returns the fraction of the timer remaining time (goes from 1.0 to 0.0).

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(2.0, TimerMode::Once);
timer.tick(Duration::from_secs_f32(0.5));
assert_eq!(timer.fraction_remaining(), 0.75);
source

pub fn remaining_secs(&self) -> f32

Returns the remaining time in seconds

§Examples
use std::cmp::Ordering;
use std::time::Duration;
let mut timer = Timer::from_seconds(2.0, TimerMode::Once);
timer.tick(Duration::from_secs_f32(0.5));
let result = timer.remaining_secs().total_cmp(&1.5);
assert_eq!(Ordering::Equal, result);
source

pub fn remaining(&self) -> Duration

Returns the remaining time using Duration

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(2.0, TimerMode::Once);
timer.tick(Duration::from_secs_f32(0.5));
assert_eq!(timer.remaining(), Duration::from_secs_f32(1.5));
source

pub fn times_finished_this_tick(&self) -> u32

Returns the number of times a repeating timer finished during the last tick call.

For non repeating-timers, this method will only ever return 0 or 1.

§Examples
use std::time::Duration;
let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating);
timer.tick(Duration::from_secs_f32(6.0));
assert_eq!(timer.times_finished_this_tick(), 6);
timer.tick(Duration::from_secs_f32(2.0));
assert_eq!(timer.times_finished_this_tick(), 2);
timer.tick(Duration::from_secs_f32(0.5));
assert_eq!(timer.times_finished_this_tick(), 0);

Trait Implementations§

source§

impl Clone for Timer

source§

fn clone(&self) -> Timer

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

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

Performs copy-assignment from source. Read more
source§

impl Debug for Timer

source§

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

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

impl Default for Timer

source§

fn default() -> Timer

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

impl FromReflect for Timer

source§

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

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

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

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

impl GetTypeRegistration for Timer

source§

impl PartialEq for Timer

source§

fn eq(&self, other: &Timer) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Reflect for Timer

source§

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

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

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

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

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

Returns the value as a &dyn Any.
source§

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

Returns the value as a &mut dyn Any.
source§

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

Casts this type to a boxed reflected value.
source§

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

Casts this type to a reflected value.
source§

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

Casts this type to a mutable reflected value.
source§

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

Clones the value as a Reflect trait object. Read more
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§

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

Applies 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<Timer>) -> ReflectOwned

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

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

Returns a “partial equality” comparison result. Read more
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 serializable(&self) -> Option<Serializable<'_>>

Returns a serializable version of the value. Read more
source§

fn is_dynamic(&self) -> bool

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

impl Struct for Timer

source§

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

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

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

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

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

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

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

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

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

Returns the name of the field with index index.
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 clone_dynamic(&self) -> DynamicStruct

Clones the struct into a DynamicStruct.
source§

impl TypePath for Timer
where Timer: 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 Typed for Timer

source§

fn type_info() -> &'static TypeInfo

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

impl Eq for Timer

source§

impl StructuralPartialEq for Timer

Auto Trait Implementations§

§

impl Freeze for Timer

§

impl RefUnwindSafe for Timer

§

impl Send for Timer

§

impl Sync for Timer

§

impl Unpin for Timer

§

impl UnwindSafe for Timer

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<Image>) -> 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<T> Downcast<T> for T

source§

fn downcast(&self) -> &T

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> 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<T> DynEq for T
where T: Any + Eq,

source§

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

Casts the type to dyn Any.
source§

fn dyn_eq(&self, other: &(dyn DynEq + 'static)) -> bool

This method tests for self and other values to be equal. Read more
source§

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

source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> FromWorld for T
where T: Default,

source§

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

Creates Self using data from the given World.
source§

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

source§

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

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

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

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

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

source§

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

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

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

Returns a mutable reference to the value specified by path. Read more
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> 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> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

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

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

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

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

source§

fn to_sample_(self) -> U

source§

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

§

type Error = Infallible

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

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

Performs the conversion.
source§

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

§

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

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

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

Performs the conversion.
source§

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

source§

impl<T> Upcast<T> for T

source§

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

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

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

source§

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

source§

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

source§

impl<T> WasmNotSendSync for T

source§

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