How do I spawn a single instance in a random position?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Finboror

I’m making a procedurally generated 3D dungeon crawler. I generated the level with GridMaps. In each level, there’s meant to be a single merchant you can buy stuff from and a single exit to the next level.

I want these to randomly spawn on the floor of the level. I have some ideas, but none I can succesfully translate to code. The most obvious one is to choose a random floor tile and spawn it there. However, as I said, my brain capacity isn’t enough to turn that to actual code that works. Any help? Thanks in advance

:bust_in_silhouette: Reply From: andersmmg

Depending on your current code, you can probably do something like this

var new_one = merchant.instance()
get_tree().get_root().add_child(new_one)
new_one.global_translate = selected_tile.global_translate

Much of it depends on the structure of your project, but something like this should help you get it working

Hmm, interesting! My biggest problem is choosing the random floor tile where the merchant spawns. The floor tiles are a different MeshInstance than the ceiling or the walls.

Here’s my code:

    func _ready():
#Cave generation
	randomize()
	var current_pos = Vector2(0,0)

	var current_dir = Vector2.DOWN
	var last_dir = current_dir * -1

	for x in grid_size:
		for y in grid_size:
		# flood the entire grid from Vector3(0, 1, 0) to Vector3(120, 1, 120)
			$Navigation/GridMap.set_cell_item(x -40, 1, y -70, 0)
			$Navigation/GridMap.set_cell_item(x -40, 2, y -70, 0)

	for i in range(0, grid_steps):
		var temp_dir = dir.duplicate()
		temp_dir.shuffle()
		var d = temp_dir.pop_front()

		while(abs(current_pos.x + d.x) > grid_size or abs(current_pos.y + d.y) > grid_size or d == last_dir * -1): 
			temp_dir.shuffle()
			d = temp_dir.pop_front()

		current_pos += d
		last_dir = d


		$Navigation/GridMap.set_cell_item(current_pos.x,0,current_pos.y,1) 

		$Navigation/GridMap.set_cell_item(current_pos.x,1,current_pos.y,-1)

Basically it first creates two big solid planes (ceiling and walls) and then randomly generates a floor. After that it removes tiles over the floor tiles, creating these nice tunnels

Finboror | 2021-07-06 10:00