Tips: displays a 2D grid to visualize your character moves

In the early stages of a 2D top down game developement with a following camera, it's impossible to visualize the character movement without fixing something in the background to actually see the player moving on something.

Here is a video showing the problem, you can't see it but the character is actually moving:

The most used trick is probably to load a picture in the background to visualize the movement.
But I know myself: if I start to search for a background, even if the first placeholder picture would fit for this purpose, I will spend a certain amount of time to search for the perfect background, with some grass or something that looks cool. And I'll probably change it in few days for something more appropriate...

Luckily, this could also be achieved without any asset, using gizmos!

With the tiny piece of code bellow, you'll display a 2D grid, calculated on the viewport size to visualize the moves:

Here is the snippet, you should be able to just copy/paste it inside your code:

const GRID_CELL_SIZE: Vec2 = Vec2::new(80., 80.);

fn draw_gizmos_grid(
    mut gizmos: Gizmos,
    camera_query: Query<(&Camera, &GlobalTransform)>
) {
    let (camera, global_transform) = camera_query.single();

    if let Some(viewport_size) = camera.logical_viewport_size() {
        let center = global_transform.translation().xy();
        let grid_x = (center.x / GRID_CELL_SIZE.x).round() * GRID_CELL_SIZE.x;
        let grid_y = (center.y / GRID_CELL_SIZE.y).round() * GRID_CELL_SIZE.y;
        let grid_cell_count = UVec2::new(
            (viewport_size.x / GRID_CELL_SIZE.x).ceil() as u32 + 1,
            (viewport_size.y / GRID_CELL_SIZE.y).ceil() as u32 + 1
        );

        let grid_color = Color::srgba(1., 1., 1., 0.1);
        gizmos.grid_2d(Vec2::new(grid_x, grid_y), 0., grid_cell_count, GRID_CELL_SIZE, grid_color);
    }
}

Hopefully, this snippet will save you some times!

Comments

Be the first to post a comment!

Add a comment

Preview