← Pixel Dreamer Studio

Snap buildings to the right grid cell on both sides of the origin

Use floori() to find the cell, then place the building at the center of that cell.

int() cuts toward zero, so int(-0.5 / 2.0) is 0, the same cell as +0.5. Every cell left of or behind the origin comes out one off, and the cells along the zero lines become twice as big. Use floori(x / cell_size) for the cell and put the building at (cell + 0.5) * cell_size.

The code

Raycast from the mouse to the ground as usual and give the hit position to cell_of(). Use the Vector2i it returns as the key for what is built where, and center_of() for where the building goes. Set origin if your grid does not start at (0, 0, 0).

extends Node
## Grid cells for building placement that are right on both sides of the origin.
## cell_of() is the cell under a world point (from your mouse ray), center_of() where to put the building.

@export var cell_size := 2.0  # meters
@export var origin := Vector3.ZERO  # the corner where cell (0, 0) starts


func cell_of(world: Vector3) -> Vector2i:
	var p := (world - origin) / cell_size
	return Vector2i(floori(p.x), floori(p.z))  # floori: -0.5 is cell -1, not 0


func center_of(cell: Vector2i) -> Vector3:
	return origin + Vector3((cell.x + 0.5) * cell_size, 0.0, (cell.y + 0.5) * cell_size)

What we measured

Cells 2 m wide and a mouse point every 5 cm over 12 × 12 m around the origin: 57,600 points. Two runs with the same numbers.

Why it happens

int() drops the fraction, which rounds toward zero: 1.5 becomes 1, but -1.5 becomes -1, not -2. So on the negative side every point lands one cell too close to the origin, and cells -1 and 0 merge into one. snapped() rounds to the nearest grid point, and a grid point is the corner of four cells, not a cell. floori() always rounds down, so both sides of the origin work the same way.

What to change

Effects that fill the whole building: particles that cover a building.

Ready-made city builder effects: City Builder & Construction VFX for Godot 4 has 31 presets, including foundation, upgrade, demolish, chimney smoke, coins, zones and 8 PSX versions.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: City Builder & Construction VFX has 31 presets for placing, upgrading and demolishing buildings, including foundation, chimney smoke, coins, zones and 8 PSX versions.

More how-tos for City Builder & Construction VFX: Fire or dust over a whole building

More how-tos: Game systems