I’m trying to render a checkerboard (or make a grid-based system in general) in Bevy.
I have this component:
#[derive(Debug, Component)]
/// Defines a single grid.
/// As `Cell` is a term used in Rust terminology, Grid is a better way to refer to this.
pub(crate) struct Grid(u8, u8);
impl Grid {
pub(crate) fn new(x: u8, y: u8) -> Self {
Self(x, y)
}
pub(crate) fn x(&self) -> u8 {
self.0
}
pub(crate) fn y(&self) -> u8 {
self.1
}
pub(crate) fn indices(&self) -> (u8, u8) {
(self.x(), self.y())
}
}
And these startup systems:
pub(crate) fn init_grids(mut commands: Commands) {
debug!("Initializing grids...");
//| initializing grids up to u8::MAX
for x in 0..u8::MAX {
for y in 0..u8::MAX {
commands.spawn(Grid::new(x, y));
}
}
}
pub(crate) fn paint_grids(
grid_query: Query<&Grid>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
debug!("Painting grids...");
//| iterating over each grid
for grid in grid_query.iter() {
//| unpack x and y val of the grid
let (grid_x, grid_y) = grid.indices();
//| choose color black or white based on grid x and y value
let color = if (grid_x + grid_y) % 2 == 0 {
Color::BLACK
} else {
Color::WHITE
};
//| define grid's pixel position
let pos_x = grid_x * GRID_SIZE;
let pos_y = grid_y * GRID_SIZE;
//| create a rectangle
let mesh_handler =
Mesh2dHandle(meshes.add(Rectangle::new(GRID_SIZE as f32, GRID_SIZE as f32)));
//| draw the rectangle
commands.spawn(MaterialMesh2dBundle {
mesh: mesh_handler,
material: materials.add(color), //| define its color
transform: Transform::from_xyz(pos_x as f32, pos_y as f32, 0.0), //| define its pos in the screen
..Default::default()
});
}
}
…where GRID_SIZE
is a u8
constant and its value is 16
.
DefaultPlugins
and Camera2dBundle
are already initialized, but I get a plain gray screen.
I’m kind of new to Bevy (not to Rust), so I was wondering if there’s something I’m missing here.
Thanks in advance.
Environment
- Bevy 0.13.2
- Rust 1.76.0