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    // Set singleton
19    world.set(Gravity { value: 9.81 });
20
21    // Set Velocity
22    world.entity_named("e1").set(Velocity { x: 0.0, y: 0.0 });
23    world.entity_named("e2").set(Velocity { x: 0.0, y: 1.0 });
24    world.entity_named("e3").set(Velocity { x: 0.0, y: 2.0 });
25
26    // Create query that matches Gravity as singleton
27    let query = world
28        .query::<(&mut Velocity, &Gravity)>()
29        .term_at(1)
30        .singleton()
31        .build();
32
33    // In a query string expression you can use the $ shortcut for singletons:
34    //   Velocity, Gravity($)
35
36    query.each_entity(|entity, (velocity, gravity)| {
37        velocity.y += gravity.value;
38        println!("Entity {} has {:?}", entity.path().unwrap(), velocity);
39    });
40
41    // Output:
42    // Entity ::e1 has Velocity { x: 0.0, y: 9.81 }
43    // Entity ::e2 has Velocity { x: 0.0, y: 10.81 }
44    // Entity ::e3 has Velocity { x: 0.0, y: 11.81 }
45}
46
47#[cfg(feature = "flecs_nightly_tests")]
48#[test]
49fn test() {
50    let output_capture = OutputCapture::capture().unwrap();
51    main();
52    output_capture.test("query_singleton".to_string());
53}