Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_ecs/examples/change_detection.rs
6598 views
1
//! In this example we will simulate a population of entities. In every tick we will:
2
//! 1. spawn a new entity with a certain possibility
3
//! 2. age all entities
4
//! 3. despawn entities with age > 2
5
//!
6
//! To demonstrate change detection, there are some console outputs based on changes in
7
//! the `EntityCounter` resource and updated Age components
8
9
#![expect(
10
clippy::std_instead_of_core,
11
clippy::print_stdout,
12
reason = "Examples should not follow this lint"
13
)]
14
15
use bevy_ecs::prelude::*;
16
use rand::Rng;
17
use std::ops::Deref;
18
19
fn main() {
20
// Create a new empty World to hold our Entities, Components and Resources
21
let mut world = World::new();
22
23
// Add the counter resource to remember how many entities where spawned
24
world.insert_resource(EntityCounter { value: 0 });
25
26
// Create a new Schedule, which stores systems and controls their relative ordering
27
let mut schedule = Schedule::default();
28
29
// Add systems to the Schedule to execute our app logic
30
// We can label our systems to force a specific run-order between some of them
31
schedule.add_systems((
32
spawn_entities.in_set(SimulationSystems::Spawn),
33
print_counter_when_changed.after(SimulationSystems::Spawn),
34
age_all_entities.in_set(SimulationSystems::Age),
35
remove_old_entities.after(SimulationSystems::Age),
36
print_changed_entities.after(SimulationSystems::Age),
37
));
38
39
// Simulate 10 frames in our world
40
for iteration in 1..=10 {
41
println!("Simulating frame {iteration}/10");
42
schedule.run(&mut world);
43
}
44
}
45
46
// This struct will be used as a Resource keeping track of the total amount of spawned entities
47
#[derive(Debug, Resource)]
48
struct EntityCounter {
49
pub value: i32,
50
}
51
52
// This struct represents a Component and holds the age in frames of the entity it gets assigned to
53
#[derive(Component, Default, Debug)]
54
struct Age {
55
frames: i32,
56
}
57
58
// System sets can be used to group systems and configured to control relative ordering
59
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
60
enum SimulationSystems {
61
Spawn,
62
Age,
63
}
64
65
// This system randomly spawns a new entity in 60% of all frames
66
// The entity will start with an age of 0 frames
67
// If an entity gets spawned, we increase the counter in the EntityCounter resource
68
fn spawn_entities(mut commands: Commands, mut entity_counter: ResMut<EntityCounter>) {
69
if rand::rng().random_bool(0.6) {
70
let entity_id = commands.spawn(Age::default()).id();
71
println!(" spawning {entity_id:?}");
72
entity_counter.value += 1;
73
}
74
}
75
76
// This system prints out changes in our entity collection
77
// For every entity that just got the Age component added we will print that it's the
78
// entities first birthday. These entities where spawned in the previous frame.
79
// For every entity with a changed Age component we will print the new value.
80
// In this example the Age component is changed in every frame, so we don't actually
81
// need the `Changed` here, but it is still used for the purpose of demonstration.
82
fn print_changed_entities(
83
entity_with_added_component: Query<Entity, Added<Age>>,
84
entity_with_mutated_component: Query<(Entity, &Age), Changed<Age>>,
85
) {
86
for entity in &entity_with_added_component {
87
println!(" {entity} has its first birthday!");
88
}
89
for (entity, value) in &entity_with_mutated_component {
90
println!(" {entity} is now {value:?} frames old");
91
}
92
}
93
94
// This system iterates over all entities and increases their age in every frame
95
fn age_all_entities(mut entities: Query<&mut Age>) {
96
for mut age in &mut entities {
97
age.frames += 1;
98
}
99
}
100
101
// This system iterates over all entities in every frame and despawns entities older than 2 frames
102
fn remove_old_entities(mut commands: Commands, entities: Query<(Entity, &Age)>) {
103
for (entity, age) in &entities {
104
if age.frames > 2 {
105
println!(" despawning {entity} due to age > 2");
106
commands.entity(entity).despawn();
107
}
108
}
109
}
110
111
// This system will print the new counter value every time it was changed since
112
// the last execution of the system.
113
fn print_counter_when_changed(entity_counter: Res<EntityCounter>) {
114
if entity_counter.is_changed() {
115
println!(
116
" total number of entities spawned: {}",
117
entity_counter.deref().value
118
);
119
}
120
}
121
122