Skip to main content

examples/queries/
query_world_query.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Debug, Component)]
6pub struct Position {
7    pub x: f32,
8    pub y: f32,
9}
10
11#[derive(Debug, Component)]
12pub struct Velocity {
13    pub x: f32,
14    pub y: f32,
15}
16
17fn main() {
18    let world = World::new();
19
20    // Create a few test entities for a Position, Velocity query
21    world
22        .entity_named("e1")
23        .set(Position { x: 10.0, y: 20.0 })
24        .set(Velocity { x: 1.0, y: 2.0 });
25
26    world
27        .entity_named("e2")
28        .set(Position { x: 10.0, y: 20.0 })
29        .set(Velocity { x: 3.0, y: 4.0 });
30
31    // This entity will not match as it does not have Position, Velocity
32    world.entity_named("e3").set(Position { x: 10.0, y: 20.0 });
33
34    // Ad hoc queries are bit slower to iterate than flecs::query, but are
35    // faster to create, and in most cases require no allocations. Under the
36    // hood this API uses flecs::query, which can be used directly for more
37    // complex queries.
38
39    world.each_entity::<(&mut Position, &Velocity)>(|entity, (pos, vel)| {
40        pos.x += vel.x;
41        pos.y += vel.y;
42        println!("Entity {}: {:?}", entity.name(), pos);
43    });
44
45    // Output:
46    //  Entity e1: Position { x: 11.0, y: 22.0 }
47    //  Entity e2: Position { x: 13.0, y: 24.0 }
48}
49
50#[cfg(feature = "flecs_nightly_tests")]
51#[test]
52fn test() {
53    let output_capture = OutputCapture::capture().unwrap();
54    main();
55    output_capture.test("query_world_query".to_string());
56}