9 months ago - SDGNelson - Direct link

A friend recently asked me for advice on implementing character movement aligned with a tile map grid in Godot. This post is an explanation of the approach I would use.

To elaborate further on the requirements: The character should always end up in the center of a grid cell and can only move horizontally or vertically.

Video demonstrating the end result. (Project files at bottom of post.)

I’m generally hesitant to rely heavily on any game engine’s physics engine. For example, I wouldn’t trust a character collider the same size as a cell to fit correctly through a one-cell tall corridor.

That said, I think it’s helpful to work within the physics system so that features like ray casts, collision areas, rigid bodies, etc., interact with the character.

My first thought was for the character to always be in the center of a cell, move between cells once per physics tick, and interpolate the visuals to catch up. However, moving one cell per tick complicates characters of different speeds and could trigger a collision event much sooner than the character visual would indicate.

Instead, to get the best of both worlds, we can calculate a whole number of physics ticks for a given speed in tiles per second and incrementally move the character until centered in a grid cell again. At any given moment, we know precisely which cell we are coming from and which cell we are going to, and we can make gameplay decisions about which cells are walkable rather than relying on collisions.

Here’s the complete CharacterBody2D extension script:

And here’s a download of the project files: grid_movement.zip