Help with instancing objects

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

Hello all, how can I set the position of one object instanced by code?
Like this:

var monstro = monstros.instance()
	self.add_child(monstro)

I’ll instance 1-3 monsters per time.

Thx guys :smiley: and I was thinking how can I instance the monsters like this:
enter image description here

1 = 1 monster
2 = 2 monsters
3 = 3 monsters

I was trying to set the position like Vector2(480, 250 + (i*30)), but just work for 3 monsters :confused:

DarlesLSF | 2019-11-21 10:22

try:

var number_of_monsters=2
for i in range(number_of_monsters):
    ...

Although I do not understand the objective well, if you want to upload the relevant code so we can help you better

estebanmolca | 2019-11-21 15:36

:bust_in_silhouette: Reply From: AiTechEye

This works for both 2D and 3D (Vector2(0,5) and Vector3(0,5,7))
for local

monstro.transform.origin = Vector3(0,5,7)

or global

monstro.global_transform.origin = Vector3(0,5,7)
:bust_in_silhouette: Reply From: estebanmolca

monstro.position= Vector2(100,150) it should work

you can also do something like:

    var monstro=[]
    for i in range(3):
    	monstro.append(monstros.instance())
    	monstro[i].position=Vector2(100+i*50,100)
    	add_child(monstro[i])
    monstro[0].position=Vector2(20,20)
:bust_in_silhouette: Reply From: estebanmolca

If I did not misunderstand it is something like this:
Heigt

func _ready():
    spawn_monsters(1,600,200)
            	        	
func spawn_monsters(numberOfMonsters, heigth, posx):
     for i in range(numberOfMonsters):
     monstro.append(monsters.instance())
     monstro[i].position=Vector2(posx,(heigth/(numberOfMonsters+1))*(i+1))
     add_child(monstro[i])

Height defines the total height where they are distributed equally according to the number of instances, you can add a value to add a margin above or use random to randomize the positions a bit