The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

0 votes

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.

in Engine by (177 points)

Thx guys :D 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 :/

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

3 Answers

0 votes
Best answer

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

by (2,260 points)
selected by
+1 vote

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)
by (200 points)
+1 vote

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)
by (2,260 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 Frequently asked questions and 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 [email protected] with your username.