MCPcopy Create free account
hub / github.com/Seldom-SE/seldom_map_nav / init

Function init

examples/nav.rs:23–73  ·  view source on GitHub ↗
(mut commands: Commands, asset_server: Res<AssetServer>)

Source from the content-addressed store, hash-verified

21const PLAYER_CLEARANCE: f32 = 8.;
22
23fn init(mut commands: Commands, asset_server: Res<AssetServer>) {
24 commands.spawn((
25 Camera2d,
26 // Centering the camera
27 Transform::from_translation((MAP_SIZE.as_vec2() * TILE_SIZE / 2.).extend(999.9)),
28 ));
29
30 let mut rng = thread_rng();
31 // Randomly generate the tilemap
32 let tilemap = [(); (MAP_SIZE.x * MAP_SIZE.y) as usize].map(|_| match rng.gen_bool(0.8) {
33 true => Navability::Navable,
34 false => Navability::Solid,
35 });
36 let navability = |pos: UVec2| tilemap[(pos.y * MAP_SIZE.x + pos.x) as usize];
37
38 // Spawn images for the tiles
39 let tile_image = asset_server.load("tile.png");
40 let mut player_pos = default();
41 for x in 0..MAP_SIZE.x {
42 for y in 0..MAP_SIZE.y {
43 let pos = UVec2::new(x, y);
44 if let Navability::Navable = navability(pos) {
45 let pos = UVec2::new(x, y).as_vec2() * TILE_SIZE;
46 player_pos = pos;
47
48 commands.spawn((
49 Transform::from_translation(pos.extend(0.)),
50 Sprite::from_image(tile_image.clone()),
51 Anchor::BOTTOM_LEFT,
52 ));
53 }
54 }
55 }
56
57 // Here's the important bit:
58
59 // Spawn the tilemap with a `Navmeshes` component
60 commands
61 .spawn(Navmeshes::generate(MAP_SIZE, TILE_SIZE, navability, [PLAYER_CLEARANCE]).unwrap());
62
63 // Spawn the player component. A position component is necessary. We will add `NavBundle`
64 // later.
65 commands.spawn((
66 Player,
67 Sprite {
68 image: asset_server.load("player.png"),
69 ..default()
70 },
71 Transform::from_translation((player_pos + TILE_SIZE / 2.).extend(1.)),
72 ));
73}
74
75// Navigate the player to wherever you click
76fn move_player(

Callers

nothing calls this directly

Calls 1

as_vec2Method · 0.80

Tested by

no test coverage detected