Trying to create a mini-game where you mine down and break blocks for ore. Completely stumped with the Tilemap

Godot Version



Instead of using a few thousand StaticBody2Ds, it’s best to use a TileMap. However, I am completely stumped on how to destroy the blocks near the player, and to also drop specific resources based on the tile that was destroyed.

I could rather easily do it with StaticBodies, but Tilemap confuses me. I managed to instantly remove/destroy some tilemap blocks with the code below. However, it works strangely. Only if I am pointing with my mouse the raycast towards the right side or down would it remove a tile. Otherwise, it does nothing.

Would love any help and any pointers towards implementing a mining system! I am obviously not expecting a full solution, but any tips would be great. I am just lost : /

func _process(_delta):
	var mouse_position = get_global_mouse_position()
	var direction_to_mouse = (mouse_position - global_position).normalized()
	var direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	velocity = direction * movement_speed
	$RayCast2D.rotation = direction_to_mouse.angle()
	if Input.is_action_just_pressed("primary"):
		var global_collision_point = $RayCast2D.get_collision_point()
		var tile_map = %TileMap
		if tile_map != null:
			var local_collision_point = tile_map.to_local(global_collision_point)
			var cell_pos = tile_map.local_to_map(local_collision_point)
			tile_map.set_cell(0, cell_pos, -1)

I don’t know what you mean by “it works strangely” but when I read your script, I’ve seen an error : var tile_map = %TileMap

If you want to get the child “TileMap”, you have to write this : var tile_map = $TileMap

Sorry if my english is a little bit bad because I’m french

Im.not at home right now so i dont have access to my code but im doing a similar game and the easiest way to do destructible blocks is by getting the mouse position and storing it in a variable and then doing a LocalToMap() passing in the mouse position variable. That gives you the mousePOS and tilePOS variables you need to make this code work.

1 Like

I see! Working with the mouse position works indeed! Not sure why it’s hard to make it work with the RayCast2D, but mouse pos will do! Thanks ^^

Normally, you’d use “$” indeed. However, I had that TileMap node set as “Access as unique name”, and in that case, you use the “%” symbol.

1 Like

Glad you got it working. Its funny to see this code as compared to the function now it is so basic lol.

1 Like