How do I get objects to randomly spawn at specific coordinates? GDscript

Attention Topic was automatically imported from the old Question2Answer platform.

Let’s say I wanted to only spawn something on these dots (coordinates) let’s say %50 of the time:

| .|
| .|
| .|
| .|

How would I do that?

You need to have an Array of finite positions, like

``````var positions = [Vector2(0,0),Vector2(25,0),Vector2(0,25),Vector2(25,25)]
``````

So You can loop through it and apply any random choices :
#pseudocode
for pos in positions :
if randi_range(100) > 50 :
instantiate somoething
something.global_position = pos

If You don’t have knowledge about random functions, take a look into documentation at RandomNumberGenerator

You can create and set the position like this

``````var object = load(res://objectYouWantToSpawn.tscn)
var newobject = object.instance()
newobject.set_position(dot)
``````

dot would be a Vector2 containing the position you want to put the spawn.
You can take the code from the ready function and put it inside any script.
From this question I’m not sure if you want it to pick from a group of positions or just a random point on the screen.
For this example I’m going to make it pick from the coordinates 10,10 20,20 30,30 and 40,40
You would put the below code above position = dot.

``````var random = rand_range(0,4)
if random < 1:
var dot = Vector2(10,10)
elif random < 2:
var dot = Vector2(20,20)
elif random < 3:
var dot = Vector2(30,30)
elif random < 4:
var dot = Vector2(40,40)
``````

or do what the Inces said to do which would be more efficient for the positions and use the ready code to instantiate the object.

Dirt ! ! | 2022-07-24 06:54