+2 votes

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?

Godot version 3.3.4
in Engine by (14 points)

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

1 Answer

0 votes

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)
by (22 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.