Skip to main content

examples/queries/
query_singleton.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4#[derive(Debug, Component)]
5struct Gravity {
6    value: f32,
7}
8
9#[derive(Debug, Component)]
10pub struct Velocity {
11    pub x: f32,
12    pub y: f32,
13}
14
15fn main() {
16    let world = World::new();
17
18    // Mark Gravity as singleton
19    world.component::<Gravity>().add_trait::<flecs::Singleton>();
20
21    // Set singleton
22    world.set(Gravity { value: 9.81 });
23
24    // Set Velocity
25    world.entity_named("e1").set(Velocity { x: 0.0, y: 0.0 });
26    world.entity_named("e2").set(Velocity { x: 0.0, y: 1.0 });
27    world.entity_named("e3").set(Velocity { x: 0.0, y: 2.0 });
28
29    // Create query that matches Gravity as singleton
30    let query = world.query::<(&mut Velocity, &Gravity)>().build();
31
32    query.each_entity(|entity, (velocity, gravity)| {
33        velocity.y += gravity.value;
34        println!("Entity {} has {:?}", entity.path().unwrap(), velocity);
35    });
36
37    // Output:
38    // Entity ::e1 has Velocity { x: 0.0, y: 9.81 }
39    // Entity ::e2 has Velocity { x: 0.0, y: 10.81 }
40    // Entity ::e3 has Velocity { x: 0.0, y: 11.81 }
41}
42
43#[cfg(feature = "flecs_nightly_tests")]
44#[test]
45fn test() {
46    let output_capture = OutputCapture::capture().unwrap();
47    main();
48    output_capture.test("query_singleton".to_string());
49}