2020-04-28 20:46:07 +00:00
|
|
|
use bevy::prelude::*;
|
2020-04-28 18:25:24 +00:00
|
|
|
|
2020-04-28 20:46:07 +00:00
|
|
|
/// Illustrates the different ways you can declare systems
|
2020-04-28 18:25:24 +00:00
|
|
|
fn main() {
|
|
|
|
App::build()
|
|
|
|
.add_default_plugins()
|
2020-04-28 20:46:07 +00:00
|
|
|
.add_event::<MyEvent>()
|
|
|
|
.add_startup_system(setup)
|
2020-04-29 06:02:21 +00:00
|
|
|
.add_system_init(built_system)
|
2020-04-30 19:22:35 +00:00
|
|
|
.add_system(simple_system.system())
|
2020-04-29 06:02:21 +00:00
|
|
|
.add_system(closure_system())
|
2020-04-28 18:25:24 +00:00
|
|
|
.run();
|
|
|
|
}
|
|
|
|
|
2020-04-28 20:46:07 +00:00
|
|
|
struct MyEvent(usize);
|
|
|
|
|
|
|
|
// resources
|
|
|
|
struct A(usize);
|
|
|
|
|
|
|
|
// components
|
|
|
|
struct X(usize);
|
|
|
|
struct Y(usize);
|
|
|
|
|
|
|
|
// add our resources and entities
|
|
|
|
fn setup(world: &mut World, resources: &mut Resources) {
|
|
|
|
resources.insert(A(0));
|
|
|
|
world.insert((), vec![(X(0), Y(1)), (X(2), Y(3))]);
|
|
|
|
}
|
|
|
|
|
2020-04-29 06:02:21 +00:00
|
|
|
// runs once for each entity with the X and Y component
|
|
|
|
fn simple_system(x: Ref<X>, mut y: RefMut<Y>) {
|
|
|
|
y.0 += 1;
|
|
|
|
println!("processed entity: {} {}", x.0, y.0);
|
2020-04-28 20:46:07 +00:00
|
|
|
}
|
|
|
|
|
2020-04-29 06:02:21 +00:00
|
|
|
// does the same thing as the first system, but also captures the "counter" variable and uses it as internal state
|
|
|
|
fn closure_system() -> Box<dyn Schedulable> {
|
|
|
|
let mut counter = 0;
|
|
|
|
(move |x: Ref<X>, mut y: RefMut<Y>| {
|
|
|
|
y.0 += 1;
|
|
|
|
println!("processed entity: {} {}", x.0, y.0);
|
|
|
|
println!("ran {} times", counter);
|
|
|
|
counter += 1;
|
2020-04-29 08:37:54 +00:00
|
|
|
})
|
2020-04-30 19:22:35 +00:00
|
|
|
.system()
|
2020-04-29 06:02:21 +00:00
|
|
|
}
|
2020-04-28 20:46:07 +00:00
|
|
|
|
2020-04-29 06:02:21 +00:00
|
|
|
// if you need more flexibility, you can define complex systems using the system builder
|
|
|
|
fn built_system(resources: &mut Resources) -> Box<dyn Schedulable> {
|
2020-04-28 20:46:07 +00:00
|
|
|
let mut my_event_reader = resources.get_event_reader::<MyEvent>();
|
|
|
|
SystemBuilder::new("example")
|
|
|
|
.read_resource::<Events<MyEvent>>()
|
|
|
|
.write_resource::<A>()
|
|
|
|
.with_query(<(Read<X>, Write<Y>)>::query())
|
2020-04-29 06:02:21 +00:00
|
|
|
.build(
|
|
|
|
move |_command_buffer, world, (my_events, ref mut a), query| {
|
|
|
|
for event in my_event_reader.iter(&my_events) {
|
|
|
|
a.0 += event.0;
|
|
|
|
println!("modified resource A with event: {}", event.0);
|
|
|
|
}
|
|
|
|
for (x, mut y) in query.iter_mut(world) {
|
|
|
|
y.0 += 1;
|
|
|
|
println!("processed entity: {} {}", x.0, y.0);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
)
|
2020-04-28 18:25:24 +00:00
|
|
|
}
|