adapt examples to use system functions and state pattern

This commit is contained in:
Carter Anderson 2020-04-30 13:52:11 -07:00
parent 98f9639050
commit 2447672c63
11 changed files with 94 additions and 93 deletions

View File

@ -4,7 +4,7 @@ pub mod system;
use bevy_app::{AppBuilder, AppPlugin}; use bevy_app::{AppBuilder, AppPlugin};
use keyboard::KeyboardInput; use keyboard::KeyboardInput;
use mouse::{MouseButtonInput, MouseMotion}; use mouse::{MouseButtonInput, MouseMotionInput};
#[derive(Default)] #[derive(Default)]
pub struct InputPlugin; pub struct InputPlugin;
@ -13,6 +13,6 @@ impl AppPlugin for InputPlugin {
fn build(&self, app: &mut AppBuilder) { fn build(&self, app: &mut AppBuilder) {
app.add_event::<KeyboardInput>() app.add_event::<KeyboardInput>()
.add_event::<MouseButtonInput>() .add_event::<MouseButtonInput>()
.add_event::<MouseMotion>(); .add_event::<MouseMotionInput>();
} }
} }

View File

@ -15,6 +15,6 @@ pub enum MouseButton {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct MouseMotion { pub struct MouseMotionInput {
pub delta: (f64, f64), pub delta: (f64, f64),
} }

View File

@ -4,7 +4,7 @@ pub use winit_windows::*;
use bevy_input::{ use bevy_input::{
keyboard::KeyboardInput, keyboard::KeyboardInput,
mouse::{MouseButtonInput, MouseMotion}, mouse::{MouseButtonInput, MouseMotionInput},
}; };
use bevy_app::{App, AppBuilder, AppExit, AppPlugin, EventReader, Events, GetEventReader}; use bevy_app::{App, AppBuilder, AppExit, AppPlugin, EventReader, Events, GetEventReader};
@ -114,8 +114,8 @@ pub fn winit_runner(mut app: App) {
event::Event::DeviceEvent { ref event, .. } => match event { event::Event::DeviceEvent { ref event, .. } => match event {
DeviceEvent::MouseMotion { delta } => { DeviceEvent::MouseMotion { delta } => {
let mut mouse_motion_events = let mut mouse_motion_events =
app.resources.get_mut::<Events<MouseMotion>>().unwrap(); app.resources.get_mut::<Events<MouseMotionInput>>().unwrap();
mouse_motion_events.send(MouseMotion { delta: *delta }); mouse_motion_events.send(MouseMotionInput { delta: *delta });
} }
_ => {} _ => {}
}, },

View File

@ -17,7 +17,7 @@ fn main() {
.add_plugin(ScheduleRunnerPlugin { .add_plugin(ScheduleRunnerPlugin {
run_mode: RunMode::Once, run_mode: RunMode::Once,
}) })
.add_system(hello_world.system()) .add_system(hello_world_system.system())
.run(); .run();
// this app loops forever at 60 fps // this app loops forever at 60 fps
@ -27,10 +27,10 @@ fn main() {
wait: Some(Duration::from_secs_f64(1.0 / 60.0)), wait: Some(Duration::from_secs_f64(1.0 / 60.0)),
}, },
}) })
.add_system(hello_world.system()) .add_system(hello_world_system.system())
.run(); .run();
} }
pub fn hello_world() { fn hello_world_system() {
println!("hello world"); println!("hello world");
} }

View File

@ -3,10 +3,10 @@ use bevy::prelude::*;
fn main() { fn main() {
App::build() App::build()
.add_default_plugins() .add_default_plugins()
.add_system(hello_world.system()) .add_system(hello_world_system.system())
.run(); .run();
} }
pub fn hello_world() { fn hello_world_system() {
println!("hello world"); println!("hello world");
} }

View File

@ -6,53 +6,60 @@ use bevy::{
fn main() { fn main() {
App::build() App::build()
.add_default_plugins() .add_default_plugins()
.add_system_init(move_on_input_system) .add_resource_init::<State>()
.add_system(collect_input_system.system())
.add_system(move_system.system())
.add_startup_system(setup) .add_startup_system(setup)
.run(); .run();
} }
#[derive(Resource)]
struct State {
event_reader: EventReader<KeyboardInput>,
moving_right: bool,
moving_left: bool,
}
/// adjusts move state based on keyboard input
fn collect_input_system(
mut state: ResourceMut<State>,
keyboard_input_events: Resource<Events<KeyboardInput>>,
) {
for event in state.event_reader.iter(&keyboard_input_events) {
match event {
KeyboardInput {
virtual_key_code: Some(VirtualKeyCode::Left),
state: element_state,
..
} => {
state.moving_left = element_state.is_pressed();
}
KeyboardInput {
virtual_key_code: Some(VirtualKeyCode::Right),
state: element_state,
..
} => {
state.moving_right = element_state.is_pressed();
}
_ => {}
}
}
}
/// moves our cube left when the "left" key is pressed. moves it right when the "right" key is pressed /// moves our cube left when the "left" key is pressed. moves it right when the "right" key is pressed
pub fn move_on_input_system(resources: &mut Resources) -> Box<dyn Schedulable> { fn move_system(
let mut keyboard_input_event_reader = resources.get_event_reader::<KeyboardInput>(); state: Resource<State>,
let mut moving_left = false; time: Resource<Time>,
let mut moving_right = false; mut translation: RefMut<Translation>,
SystemBuilder::new("input_handler") _: Ref<Handle<Mesh>>,
.read_resource::<Time>() ) {
.read_resource::<Events<KeyboardInput>>() if state.moving_left {
.with_query(<(Write<Translation>, Read<Handle<Mesh>>)>::query()) translation.0 += math::vec3(1.0, 0.0, 0.0) * time.delta_seconds;
.build( }
move |_command_buffer, world, (time, keyboard_input_events), mesh_query| {
for event in keyboard_input_event_reader.iter(&keyboard_input_events) {
match event {
KeyboardInput {
virtual_key_code: Some(VirtualKeyCode::Left),
state,
..
} => {
moving_left = state.is_pressed();
}
KeyboardInput {
virtual_key_code: Some(VirtualKeyCode::Right),
state,
..
} => {
moving_right = state.is_pressed();
}
_ => {}
}
}
for (mut translation, _mesh) in mesh_query.iter_mut(world) { if state.moving_right {
if moving_left { translation.0 += math::vec3(-1.0, 0.0, 0.0) * time.delta_seconds;
translation.0 += math::vec3(1.0, 0.0, 0.0) * time.delta_seconds; }
}
if moving_right {
translation.0 += math::vec3(-1.0, 0.0, 0.0) * time.delta_seconds;
}
}
},
)
} }
/// creates a simple scene /// creates a simple scene

View File

@ -1,34 +1,36 @@
use bevy::{ use bevy::{
input::mouse::{MouseButtonInput, MouseMotion}, input::mouse::{MouseButtonInput, MouseMotionInput},
prelude::*, prelude::*,
}; };
fn main() { fn main() {
App::build() App::build()
.add_default_plugins() .add_default_plugins()
.add_system_init(mouse_input_system) .add_resource_init::<State>()
.add_system(mouse_input_system.system())
.run(); .run();
} }
/// prints out mouse events as they come in #[derive(Resource)]
pub fn mouse_input_system(resources: &mut Resources) -> Box<dyn Schedulable> { struct State {
let mut mouse_button_input_event_reader = resources.get_event_reader::<MouseButtonInput>(); mouse_button_event_reader: EventReader<MouseButtonInput>,
let mut mouse_motion_event_reader = resources.get_event_reader::<MouseMotion>(); mouse_motion_event_reader: EventReader<MouseMotionInput>,
SystemBuilder::new("mouse_input") }
.read_resource::<Events<MouseButtonInput>>()
.read_resource::<Events<MouseMotion>>() /// prints out mouse events as they come in
.build( fn mouse_input_system(
move |_command_buffer, mut state: ResourceMut<State>,
_world, mouse_button_input_events: Ref<Events<MouseButtonInput>>,
(mouse_button_input_events, mouse_motion_events), mouse_motion_events: Ref<Events<MouseMotionInput>>,
_queries| { ) {
for event in mouse_button_input_event_reader.iter(&mouse_button_input_events) { for event in state
println!("{:?}", event); .mouse_button_event_reader
} .iter(&mouse_button_input_events)
{
for event in mouse_motion_event_reader.iter(&mouse_motion_events) { println!("{:?}", event);
println!("{:?}", event); }
}
}, for event in state.mouse_motion_event_reader.iter(&mouse_motion_events) {
) println!("{:?}", event);
}
} }

View File

@ -6,12 +6,12 @@ fn main() {
App::build() App::build()
.add_default_plugins() .add_default_plugins()
.add_startup_system(setup) .add_startup_system(setup)
.add_system(rotator.system()) .add_system(rotator_system.system())
.run(); .run();
} }
/// rotates the parent, which will result in the child also rotating /// rotates the parent, which will result in the child also rotating
fn rotator(time: Resource<Time>, _rotator: RefMut<Rotator>, mut rotation: RefMut<Rotation>) { fn rotator_system(time: Resource<Time>, _rotator: RefMut<Rotator>, mut rotation: RefMut<Rotation>) {
rotation.0 = rotation.0 * Quat::from_rotation_x(3.0 * time.delta_seconds); rotation.0 = rotation.0 * Quat::from_rotation_x(3.0 * time.delta_seconds);
} }

View File

@ -35,7 +35,7 @@ fn main() {
#[derive(Serialize, Deserialize, TypeUuid)] #[derive(Serialize, Deserialize, TypeUuid)]
#[uuid = "14dec17f-ae14-40a3-8e44-e487fc423287"] #[uuid = "14dec17f-ae14-40a3-8e44-e487fc423287"]
pub struct Test { struct Test {
pub x: f32, pub x: f32,
pub y: f32, pub y: f32,
} }

View File

@ -3,14 +3,14 @@ use bevy::prelude::*;
fn main() { fn main() {
App::build() App::build()
.add_default_plugins() .add_default_plugins()
.add_startup_system(startup.system()) .add_startup_system(startup_system.system())
.run(); .run();
} }
/// Set up a simple scene using a "startup system". /// Set up a simple scene using a "startup system".
/// Startup systems are run exactly once when the app starts up. /// Startup systems are run exactly once when the app starts up.
/// They run right before "normal" systems run. /// They run right before "normal" systems run.
fn startup( fn startup_system(
command_buffer: &mut CommandBuffer, command_buffer: &mut CommandBuffer,
mut meshes: ResourceMut<AssetStorage<Mesh>>, mut meshes: ResourceMut<AssetStorage<Mesh>>,
mut materials: ResourceMut<AssetStorage<StandardMaterial>>, mut materials: ResourceMut<AssetStorage<StandardMaterial>>,

View File

@ -4,7 +4,7 @@ fn main() {
App::build() App::build()
.add_default_plugins() .add_default_plugins()
.add_startup_system(setup) .add_startup_system(setup)
.add_system(build_move_system()) .add_system(move_system.system())
.add_plugin(DiagnosticsPlugin { .add_plugin(DiagnosticsPlugin {
print_diagnostics: true, print_diagnostics: true,
..Default::default() ..Default::default()
@ -12,18 +12,10 @@ fn main() {
.run(); .run();
} }
fn build_move_system() -> Box<dyn Schedulable> { fn move_system(time: Resource<Time>, mut node: RefMut<Node>) {
SystemBuilder::new("move") if node.color.r > 0.2 {
.read_resource::<Time>() node.position += Vec2::new(0.1 * time.delta_seconds, 0.0);
.with_query(<Write<Node>>::query()) }
.build(move |_, world, time, query| {
for (_i, mut node) in query.iter_mut(world).enumerate() {
if node.color.r > 0.2 {
node.position += Vec2::new(0.1 * time.delta_seconds, 0.0);
// println!("{}", node.position.x());
}
}
})
} }
fn setup(world: &mut World, _resources: &mut Resources) { fn setup(world: &mut World, _resources: &mut Resources) {