Skip to main content

examples/observers/
observer_two_components.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
17// An observer can match multiple components/tags. Only entities that match the
18// entire observer query will be forwarded to the callback. For example, an
19// observer for Position,Velocity won't match an entity that only has Position.
20
21fn main() {
22    let world = World::new();
23
24    // Create observer for custom event
25    world
26        .observer::<flecs::OnSet, (&Position, &Velocity)>()
27        .each_iter(|it, index, (pos, vel)| {
28            println!(
29                " - {}: {}: {}: p: {{ {}, {} }}, v: {{ {}, {} }}",
30                it.event().name(),
31                it.event_id().to_str(),
32                it.entity(index).name(),
33                pos.x,
34                pos.y,
35                vel.x,
36                vel.y
37            );
38        });
39
40    // Create entity, set Position (emits EcsOnSet, does not yet match observer)
41    let entity = world.entity_named("e").set(Position { x: 10.0, y: 20.0 });
42
43    // Set Velocity (emits EcsOnSet, matches observer)
44    entity.set(Velocity { x: 1.0, y: 2.0 });
45
46    // Output:
47    //  - OnSet: Velocity: e: p: { 10, 20 }, v: { 1, 2 }
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("observer_two_components".to_string());
56}