Skip to main content

examples/systems/
system_time_interval.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4// This example shows how to run a system at a specified time interval.
5
6#[derive(Component)]
7struct Timeout {
8    pub value: f32,
9}
10
11fn tick(mut it: TableIter) {
12    while it.next() {
13        println!("{}", it.system().name());
14    }
15}
16
17fn main() {
18    let world = World::new();
19
20    world.set(Timeout { value: 3.5 });
21
22    world
23        .system::<&mut Timeout>()
24        .each_iter(|it, _index, timeout| {
25            timeout.value -= it.delta_time();
26        });
27
28    world.system_named::<()>("Tick").set_interval(1.0).run(tick);
29
30    world
31        .system_named::<()>("FastTick")
32        .set_interval(0.5)
33        .run(tick);
34
35    // Run the main loop at 60 FPS
36    world.set_target_fps(60.0);
37
38    while world.progress() {
39        if world.get::<&Timeout>(|timeout| timeout.value <= 0.0) {
40            println!("Timed out!");
41            break;
42        }
43    }
44
45    // Output:
46    // FastTick
47    // Tick
48    // FastTick
49    // FastTick
50    // Tick
51    // FastTick
52    // FastTick
53    // Tick
54    // FastTick
55    // FastTick
56    // Timed out!
57}
58
59#[cfg(feature = "flecs_nightly_tests")]
60#[test]
61fn test() {
62    let output_capture = OutputCapture::capture().unwrap();
63    main();
64    assert!(output_capture.output_string().contains("Timed out!"));
65}