Browse Source

Add basic evented motion system

Getty Ritter 4 years ago
parent
commit
54dfd568e7
1 changed files with 11 additions and 8 deletions
  1. 11 8
      ch2/src/main.rs

+ 11 - 8
ch2/src/main.rs

@@ -30,6 +30,13 @@ pub struct Motion {
     right: i8,
 }
 
+impl Motion {
+    fn move_player(&mut specs::World, down: i8, right: i8) {
+        let player = (&world.read_component::<Player>(), &world.entities()).join().next().unwrap().1;
+        world.write_component::<Motion>().insert(player, Motion { down, right }).unwrap();
+    }
+}
+
 system_impl! {
     Draw(
         resource mut board: carpet::Board<carpet::CP437>,
@@ -110,23 +117,19 @@ fn main() -> Result<(), GameError> {
     }
 
     game.on_key((carpet::VirtualKeyCode::W, carpet::KeyMods::NONE), |world| {
-        let player = (&world.read_component::<Player>(), &world.entities()).join().next().unwrap().1;
-        world.write_component::<Motion>().insert(player, Motion { down: -1, right: 0 }).unwrap();
+        Motion::move_player(world, -1, 0);
     });
 
     game.on_key((carpet::VirtualKeyCode::A, carpet::KeyMods::NONE), |world| {
-        let player = (&world.read_component::<Player>(), &world.entities()).join().next().unwrap().1;
-        world.write_component::<Motion>().insert(player, Motion { down: 0, right: -1 }).unwrap();
+        Motion::move_player(world, 0, -1);
     });
 
     game.on_key((carpet::VirtualKeyCode::S, carpet::KeyMods::NONE), |world| {
-        let player = (&world.read_component::<Player>(), &world.entities()).join().next().unwrap().1;
-        world.write_component::<Motion>().insert(player, Motion { down: 1, right: 0 }).unwrap();
+        Motion::move_player(world, 1, 0);
     });
 
     game.on_key((carpet::VirtualKeyCode::D, carpet::KeyMods::NONE), |world| {
-        let player = (&world.read_component::<Player>(), &world.entities()).join().next().unwrap().1;
-        world.write_component::<Motion>().insert(player, Motion { down: 0, right: 1 }).unwrap();
+        Motion::move_player(world, 0, 1);
     });
 
     game.run_with_systems(|world| {