examples/
hello_world.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#[derive(Component)]
18pub struct Eats;
19
20#[derive(Component)]
21pub struct Apples;
22
23fn main() {
24    // Create a new world
25    let world = World::new();
26
27    // Register system
28    let _sys = world
29        .system::<(&mut Position, &Velocity)>()
30        // .each_entity if you want the entity to be added in the parameter list
31        .each(|(pos, vel)| {
32            pos.x += vel.x;
33            pos.y += vel.y;
34        });
35
36    // Create an entity with name Bob, add Position and food preference
37    let bob = world
38        .entity_named("Bob")
39        .set(Position { x: 0.0, y: 0.0 })
40        .set(Velocity { x: 1.0, y: 2.0 })
41        .add::<(Eats, Apples)>();
42
43    // Show us what you got
44    // println!( "{}'s got [{:?}]", bob.name(), bob.archetype());
45    println!("{}'s got [{:?}]", bob.name(), bob.archetype());
46
47    // Run systems twice. Usually this function is called once per frame
48    world.progress();
49    world.progress();
50
51    // - get panics if the component is not present, use try_get for a non-panicking version which does not run the callback.
52    // - or use Option to handle the individual component missing.
53    bob.get::<&Position>(|pos| {
54        // See if Bob has moved (he has)
55        println!("{}'s position: {:?}", bob.name(), pos);
56    });
57
58    // Option example
59    let has_run = bob.try_get::<Option<&Position>>(|pos| {
60        if let Some(pos) = pos {
61            // See if Bob has moved (he has)
62            //println!( "{}'s try_get position: {:?}", bob.name(), pos);
63            println!("{}'s try_get position: {:?}", bob.name(), pos);
64        }
65    });
66
67    if has_run {
68        println!("Bob has a position component, so the try_get callback ran.");
69    }
70
71    // Output:
72    //  Bob's got [Position, Velocity, (Identifier,Name), (Eats,Apples)]
73    //  Bob's position: Position { x: 2.0, y: 4.0 }
74    //  Bob's try_get position: Position { x: 2.0, y: 4.0 }
75    //  Bob has a position component, so the try_get callback ran.
76}
77
78#[cfg(feature = "flecs_nightly_tests")]
79#[test]
80fn test() {
81    let output_capture = OutputCapture::capture().unwrap();
82    main();
83    output_capture.test("hello world".to_string());
84}