TileMap: erase_cell() Doesn't Reduce get_used_cells().size()

Godot Version

Godot Engine v4.2.stable.official

Question

I’m creating a “simple” 2D game for practice using Godot. It’s supposed to mimic Jetpack Joyride, so it will infinitely scroll in one direction. To that end, I’m trying to set up automatic generation/extension of my tilemap as the character moves to the side.

I’m assuming that infinitely generating in one direction will eventually eat up a lot of memory, so I’m trying to also delete the tilemap cells which the player has already passed and left off screen behind them.

I have the logic set up for a single strip of ground for the character to run on. I know it works, as I’ve been able to see the cells visually being generated in front of and erased behind me, but when I print out get_used_cells(0).size() on my tilemap, it is still always increasing as I generate new cells. I would expect the size to stay relatively the same since I’m erasing a cell every time I generate a new one.

Is this expected behavior? Is there a better way to delete cells from memory if they’re never going to be on screen again?

Here’s the code I’m using for generating/erasing cells:

if not is_cell_on_screen(last_spawned_coords, 1):
	if not is_cell_on_screen(first_spawned_coords, 1):
		erase_cell(0, first_spawned_coords)
		first_spawned_coords.x += 1
	last_spawned_coords.x += 1
	set_cell(0, last_spawned_coords, 0, Vector2(5, 2))

is_cell_on_screen() is a custom func that checks if a cell’s map position is within the screen and returns a bool.
first_spawned_coords is storing the map coords of the oldest spawned cell
last_spawned_coords is storing the map coords of the newest spawned cell

Grateful for any insights!

Looks like my issue was with the cell spawning code. I was spawning more cells in front of the character than I thought so even though the cells behind the character were getting erased, the total count was still going up. Fixed code below:

if not is_cell_on_screen(first_spawned_coords, 1):
	erase_cell(0, first_spawned_coords)
	first_spawned_coords.x += 1
if is_cell_on_screen(last_spawned_coords):
	last_spawned_coords.x += 1
set_cell(0, last_spawned_coords, 0, Vector2(5, 2))

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.