game.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use ggez::{Context, GameResult};
  2. use ggez::event::EventHandler;
  3. use specs::world::WorldExt;
  4. use crate::{components,resources,sys};
  5. /// The shared values that the game state needs, specifically as the specs world
  6. pub struct MyGame {
  7. pub world: specs::World,
  8. }
  9. impl MyGame {
  10. // setup the necessary initial state for `MyGame`, inserting the
  11. // relevant resources into it
  12. pub fn setup(ctx: &mut Context) -> GameResult<MyGame> {
  13. let mut world = specs::World::new();
  14. components::register(&mut world);
  15. world.insert(ncollide2d::world::CollisionWorld::<f32, specs::Entity>::new(0.1));
  16. resources::world_from_file(&mut world, "assets/main.tmx");
  17. let image = ggez::graphics::Image::new(ctx, "/spritesheet.png")?;
  18. let mut sprites = ggez::graphics::spritebatch::SpriteBatch::new(image);
  19. sprites.set_filter(ggez::graphics::FilterMode::Nearest);
  20. world.insert(sprites);
  21. world.insert(resources::KeySet::new());
  22. Ok(MyGame { world })
  23. }
  24. }
  25. impl EventHandler for MyGame {
  26. fn update(&mut self, _ctx: &mut Context) -> GameResult<()> {
  27. sys::input::systems(self);
  28. sys::physics::systems(self);
  29. Ok(())
  30. }
  31. fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
  32. sys::drawing::systems(self, ctx)
  33. }
  34. fn key_down_event(
  35. &mut self,
  36. ctx: &mut Context,
  37. keycode: winit::VirtualKeyCode,
  38. _keymod: ggez::event::KeyMods,
  39. _repeat: bool,
  40. ) {
  41. if keycode == winit::VirtualKeyCode::Escape {
  42. ggez::event::quit(ctx);
  43. }
  44. self.world.write_resource::<resources::KeySet>().insert(keycode);
  45. }
  46. fn key_up_event(
  47. &mut self,
  48. _ctx: &mut Context,
  49. keycode: winit::VirtualKeyCode,
  50. _keymod: ggez::event::KeyMods,
  51. ) {
  52. self.world.write_resource::<resources::KeySet>().remove(&keycode);
  53. }
  54. }