physics.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. use crate::com::{Blocking, Collision, Velocity, Position};
  2. use crate::game::MyGame;
  3. use specs::{Join,RunNow};
  4. struct Intersection;
  5. impl<'a> specs::System<'a> for Intersection {
  6. type SystemData = (
  7. specs::Entities<'a>,
  8. specs::ReadStorage<'a, Position>,
  9. specs::ReadStorage<'a, Velocity>,
  10. specs::ReadStorage<'a, Blocking>,
  11. specs::WriteStorage<'a, Collision>,
  12. );
  13. fn run(&mut self, (entity, position, velocity, blocking, mut collision): Self::SystemData) {
  14. let mut spacemap = std::collections::HashMap::new();
  15. for (e, pos, _) in (&entity, &position, &blocking).join() {
  16. spacemap.insert(pos.to_grid(), e);
  17. }
  18. for (pos, vel, col) in (&position, &velocity, &mut collision).join() {
  19. if let Some(_) = spacemap.get(&pos.moved(vel).to_grid()) {
  20. col.has_collision = true;
  21. }
  22. }
  23. }
  24. }
  25. struct Physics;
  26. impl <'a> specs::System<'a> for Physics {
  27. type SystemData = (
  28. specs::ReadStorage<'a, Velocity>,
  29. specs::ReadStorage<'a, Collision>,
  30. specs::WriteStorage<'a, Position>,
  31. );
  32. fn run(&mut self, (velocity, collision, mut position): Self::SystemData) {
  33. for (vel, col, pos) in (&velocity, &collision, &mut position).join() {
  34. if !col.has_collision {
  35. pos.x += vel.dx;
  36. pos.y += vel.dy;
  37. }
  38. }
  39. }
  40. }
  41. struct ResetCollision;
  42. impl<'a> specs::System<'a> for ResetCollision {
  43. type SystemData =
  44. specs::WriteStorage<'a, Collision>;
  45. fn run(&mut self, mut collision: Self::SystemData) {
  46. for mut e in (&mut collision).join() {
  47. e.has_collision = false;
  48. }
  49. }
  50. }
  51. pub fn systems(game: &mut MyGame) {
  52. Intersection.run_now(&game.world.res);
  53. Physics.run_now(&game.world.res);
  54. ResetCollision.run_now(&game.world.res);
  55. }