bevy-playground/src/map.rs

83 lines
2.5 KiB
Rust
Raw Normal View History

2024-08-02 13:40:43 -05:00
use crate::prelude::*;
use bevy_ecs_tilemap::prelude::*;
use rand::prelude::*;
use rand_pcg::Pcg64;
use rand_seeder::Seeder;
#[derive(Component, Debug)]
pub struct Tilemap;
pub fn spawn(mut commands: Commands, assets: Res<AssetServer>) {
// let task_pool = AsyncComputeTaskPool::get();
// let task = task_pool.spawn(async move {});
let mut rng: Pcg64 = Seeder::from("stripy zebra").make_rng();
let size = TilemapSize { x: 1024, y: 1024 };
let tilemap_entity = commands.spawn_empty().id();
let mut tile_storage = TileStorage::empty(size);
let mut batch = Vec::<TileBundle>::with_capacity(size.x as usize * size.y as usize);
for x in 0..size.x {
for y in 0..size.y {
let tile_pos = TilePos { x, y };
let texture_index = TileTextureIndex(if rng.gen_range(0..1000) > 925 {
rng.gen_range(0..(16 * 8))
} else {
0
});
// let texture_index = TileTextureIndex(0);
// let tile_entity = commands
// .spawn(TileBundle {
// position: tile_pos,
// tilemap_id: TilemapId(tilemap_entity),
// texture_index,
// ..Default::default()
// })
// .id();
// let tile_entity = commands
batch.push(TileBundle {
position: tile_pos,
tilemap_id: TilemapId(tilemap_entity),
texture_index,
..Default::default()
});
// .id();
// tile_storage.set(&tile_pos, tile_entity);
}
}
commands.spawn_batch(batch);
// for tb in batch {
// tile_storage.set(&tile_pos, tile_entity);
// }
let texture_handle: Handle<Image> = assets.load("img/Tileset Grass.png");
let tile_size = TilemapTileSize { x: 16.0, y: 16.0 };
let grid_size = tile_size.into();
let map_type = TilemapType::default();
let texture = TilemapTexture::Single(texture_handle);
commands.entity(tilemap_entity).insert((
Tilemap,
TilemapBundle {
grid_size,
map_type,
size,
storage: tile_storage,
texture,
tile_size,
transform: get_tilemap_center_transform(&size, &grid_size, &map_type, f32::MIN),
..default()
},
));
}
pub fn exit(mut commands: Commands, q: Query<Entity, With<Tilemap>>) {
for id in q.iter() {
commands.entity(id).despawn_recursive();
}
}