res.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. use crate::consts;
  2. use crate::components::*;
  3. use specs::world::Builder;
  4. use std::path::Path;
  5. #[derive(Debug, Copy, Clone)]
  6. enum DrawLayer {
  7. Background,
  8. Foreground,
  9. Decoration,
  10. }
  11. static DRAW_LAYERS: [DrawLayer;3] = [
  12. DrawLayer::Background,
  13. DrawLayer::Foreground,
  14. DrawLayer::Decoration,
  15. ];
  16. pub fn world_from_file<P: AsRef<Path>>(w: &mut specs::World, path: P) {
  17. let tiled::Map {
  18. layers,
  19. ..
  20. } = tiled::parse_file(path.as_ref()).unwrap();
  21. for (phase, layer) in DRAW_LAYERS.iter().zip(layers) {
  22. for (row, y) in layer.tiles.iter().zip(0..) {
  23. for (&n, x) in row.iter().zip(0..) {
  24. if n != 0 {
  25. let x = x as f32 * consts::TILE_SIZE;
  26. let y = y as f32 * consts::TILE_SIZE;
  27. let u = ((n - 1) % 32) as u8;
  28. let v = ((n - u as u32 - 1) / 32) as u8;
  29. let mut e = w.create_entity()
  30. .with(Position { x, y })
  31. .with(Sprite { u, v });
  32. e = match phase {
  33. DrawLayer::Background => e.with(Background),
  34. DrawLayer::Foreground => e.with(Foreground),
  35. DrawLayer::Decoration => e.with(Decoration),
  36. };
  37. e.build();
  38. }
  39. }
  40. }
  41. }
  42. // create the player
  43. w.create_entity()
  44. .with(Position {
  45. x: 3.0 * consts::TILE_SIZE,
  46. y: 3.0 * consts::TILE_SIZE,
  47. })
  48. .with(Sprite { u: 8, v: 0 })
  49. .with(Velocity { dx: 0.0, dy: 0.0 })
  50. .with(Foreground)
  51. .with(Movable)
  52. .build();
  53. }