examples/queries/query_with.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(Component)]
12struct Npc;
13
14fn main() {
15 let world = World::new();
16
17 // Create a query for Position, Npc. By adding the Npc component using the
18 // "with" method, the component is not a part of the query type, and as a
19 // result does not become part of the function signatures of each and iter.
20 // This is useful for things like tags, which because they don't have a
21 // value are less useful to pass to the each/iter functions as argument.
22 let query = world.query::<&Position>().with::<&Npc>().build();
23
24 // Create a few test entities for the Position, Npc query
25 world
26 .entity_named("e1")
27 .set(Position { x: 10.0, y: 20.0 })
28 .add::<Npc>();
29
30 world
31 .entity_named("e2")
32 .set(Position { x: 10.0, y: 20.0 })
33 .add::<Npc>();
34
35 // This entity will not match as it does not have Position, Npc
36 world.entity_named("e3").set(Position { x: 10.0, y: 20.0 });
37
38 // Note how the Npc tag is not part of the each signature
39 query.each_entity(|entity, pos| {
40 println!("Entity {}: {:?}", entity.name(), pos);
41 });
42
43 // Output:
44 // Entity e1: Position { x: 10.0, y: 20.0 }
45 // Entity e2: Position { x: 10.0, y: 20.0 }
46}
47
48#[cfg(feature = "flecs_nightly_tests")]
49#[test]
50fn test() {
51 let output_capture = OutputCapture::capture().unwrap();
52 main();
53 output_capture.test("query_with".to_string());
54}