Skip to main content

tilemap_chunk_orientation/
tilemap_chunk_orientation.rs

1//! Shows a tilemap chunk rendered with a single draw call, including different orientations of tiles (rotated, mirrored) and using different tileset indices, colors, alpha and visibility to show all tile features.
2
3use bevy::{
4    image::{ImageArrayLayout, ImageLoaderSettings},
5    prelude::*,
6    sprite_render::{AlphaMode2d, TileData, TileOrientation, TilemapChunk, TilemapChunkTileData},
7};
8
9fn main() {
10    App::new()
11        .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
12        .insert_resource(ClearColor(Color::srgb(0.5, 0.5, 0.9)))
13        .add_systems(Startup, setup)
14        .run();
15}
16
17fn setup(mut commands: Commands, assets: Res<AssetServer>) {
18    let chunk_size = UVec2::splat(8);
19    let tile_display_size = UVec2::splat(64);
20
21    // We'll use each possible orientation, one per column
22    let orientation = [
23        TileOrientation::Default,
24        TileOrientation::Rotate90,
25        TileOrientation::Rotate180,
26        TileOrientation::Rotate270,
27        TileOrientation::MirrorH,
28        TileOrientation::MirrorHRotate90,
29        TileOrientation::MirrorHRotate180,
30        TileOrientation::MirrorHRotate270,
31    ];
32
33    // Show different color/alpha on each row
34    let colors = [
35        Color::WHITE,
36        Color::linear_rgb(1.0, 0.0, 0.0),
37        Color::linear_rgb(0.0, 1.0, 0.0),
38        Color::linear_rgb(0.0, 0.0, 1.0),
39        Color::linear_rgba(1.0, 0.0, 0.0, 0.25),
40        Color::linear_rgba(0.0, 1.0, 0.0, 0.25),
41        Color::linear_rgba(0.0, 0.0, 1.0, 0.25),
42        Color::linear_rgba(1.0, 1.0, 1.0, 0.5),
43    ];
44
45    let tile_data = (0..chunk_size.element_product())
46        .map(|i| {
47            let row = i / 8;
48            let col = i % 8;
49            Some(TileData {
50                // Alternate tiles per row
51                tileset_index: (row % 2) as u16,
52                color: colors[row as usize],
53                // Last (top) row is invisible
54                visible: row != 7,
55                orientation: orientation[col as usize],
56            })
57        })
58        .collect();
59
60    commands.spawn((
61        TilemapChunk {
62            chunk_size,
63            tile_display_size,
64            tileset: assets
65                .load_builder()
66                .with_settings(|settings: &mut ImageLoaderSettings| {
67                    // The tileset texture is expected to be an array of tile textures, so we tell the
68                    // `ImageLoader` that our texture is composed of 2 stacked tile images.
69                    settings.array_layout = Some(ImageArrayLayout::RowCount { rows: 2 });
70                })
71                .load("textures/arrow.png"),
72            alpha_mode: AlphaMode2d::Blend,
73        },
74        TilemapChunkTileData(tile_data),
75    ));
76
77    commands.spawn(Camera2d);
78}