Tilemap doesn't update for freed objects

Godot Version

4.4

Question

Hi! I’m trying to make a rail system similar to the one in minecraft but in 2D. To detect if there is an object where you want to place a rail I’m doing this:

var data_map = tilemap.get_cell_source_id(1, rail_pos) #rail_pos is the position of the rail that is going to be placed in the tilemap
if data_map == -1:
		#place_rail

This works perfectly except for objects in the tilemap that were previously freed. I have trees that are placed as a scene collection in the tilemap and that the player can break. The problem is that even when the trees are not there anymore it doesn’t let me place a rail where they were.
The code for the trees is this, in case you’re interested

extends StaticBody2D

@export var hp : int = 3
@export var gives : int = 3

func hit():
	hp -= 1
	vfx.damagfe_vfx($Sprite2D)
	if hp <= 0:
		dissapear()

func dissapear():
	globals.wood += gives
	$Sprite2D.hide()
	$CollisionShape2D.disabled = true
	$CPUParticles2D.emitting = true


func _on_cpu_particles_2d_finished() -> void:
	print("queue free")
	queue_free()

What can I do? Thanks!

So you check your tile map to see if you can place a rail.

I presume you also place objects on your tilemap because you are checking to see if the tile is set or not.

When you are killing an object, you free it, but you do not update your tilemap. (Use cell_erase or set_cell to -1. So when you try to place a rail, there is no object there, but your tilemap thinks there is.

Hope that helps.

Set cell

Erase cell

1 Like

Thank you so much! That worked perfectly :slight_smile:

1 Like