Procedurally spawning instances of a scene

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

I´ve already made the instances spawn at random coordinates around the player, but I can´t figure out how to limit the amount of those instances in the area. Tried saving used coordinates in an array and then, using a function that checks if the used coordinates are outside the area around the player, deleting them as the player moves. Also tried limiting the amount by using an Area2D - they kept spawning endlessly, somehow bypassing the if-statement.

Here´s how the instances are spawned:


func setEnvironment(columnStart, columnEnd, rowStart, rowEnd):

   for cy in range(rowStart, rowEnd):

	for cx in range(columnStart, columnEnd):

		var tree_chance = randi() % 100 + 1

		if tree_chance < 10:
			tree_instance = tree.instance()
			var pos = tile_map.map_to_world(Vector2(cx, cy))
			tree_instance.position.y = rand_range(pos.y - chunkWidth, pos.y + chunkWidth)
			tree_instance.position.x = rand_range(pos.x - chunkLength, pos.x + chunkLength)
			get_node("YSort").add_child(tree_instance)

column/row Start/End - corners of the “rendering” area

What do I do?

Your spawning function seems to be alright. Are you calling it every frame or only when the game starts?

aXu_AP | 2021-10-17 19:06

:bust_in_silhouette: Reply From: alexandremassaro

Maybe adding the instances to an Array, then every time you instance a new object you destroy the first instance in the array if the array size is bigger then your threshold.

Here’s an example:

var trees : Array = []
for cy in range(rowStart, rowEnd):
    for cx in range(columnStart, columnEnd):

        var tree_chance = randi() % 100 + 1

        if tree_chance < 10:
            tree_instance = tree.instance()
            var pos = tile_map.map_to_world(Vector2(cx, cy))
            tree_instance.position.y = rand_range(pos.y - chunkWidth, pos.y + chunkWidth)
            tree_instance.position.x = rand_range(pos.x - chunkLength, pos.x + chunkLength)
            trees.append(tree_instance)
            if trees.size() > 10:
                trees.pop_front().queue_free()
            get_node("YSort").add_child(tree_instance)