examples/entities/entity_basics.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 Walking;
19
20fn main() {
21 let world = World::new();
22
23 // Create an entity with name Bob
24 let bob = world
25 .entity_named("Bob")
26 // The set operation finds or creates a component, and sets it.
27 // Components are automatically registered with the world
28 .set(Position { x: 10.0, y: 20.0 })
29 // The add operation adds a component without setting a value. This is
30 // useful for tags, or when adding a component with its default value.
31 .add(Walking);
32
33 // Get the value for the Position component
34 // - get panics if the component is not present, use try_get for a non-panicking version which does not run the callback.
35 // - or use Option to handle the individual component missing.
36 bob.get::<Option<&Position>>(|pos| {
37 if let Some(pos) = pos {
38 println!("Bob's position: {pos:?}");
39 }
40 });
41
42 // Overwrite the value of the Position component
43 bob.set(Position { x: 20.0, y: 30.0 });
44
45 // Create another named entity
46 let alice = world
47 .entity_named("Alice")
48 .set(Position { x: 10.0, y: 20.0 });
49
50 // Add a tag after entity is created
51 alice.add(Walking);
52
53 // Print all of the components the entity has. This will output:
54 // Position, Walking, (Identifier,Name)
55 println!("[{}]", alice.archetype());
56
57 // Remove tag
58 alice.remove(Walking);
59
60 // Iterate all entities with position
61 world.each_entity::<&Position>(|entity, pos| {
62 println!("{} has {:?}", entity.name(), pos);
63 });
64
65 // Output:
66 // Bob's position: Position { x: 10.0, y: 20.0 }
67 // [Position, Walking, (Identifier,Name)]
68 // Alice has Position { x: 10.0, y: 20.0 }
69 // Bob has Position { x: 20.0, y: 30.0 }
70}
71
72#[cfg(feature = "flecs_nightly_tests")]
73#[test]
74fn test() {
75 let output_capture = OutputCapture::capture().unwrap();
76 main();
77 output_capture.test("entity_basics".to_string());
78}