+1 vote

Hi I know this must have been asked but I can't find what I'm looking for so reluctantly asking. I have the following.

A scene with:

| board (2d node) as root
| - pieces (2d node) that sits inside board

At top of script:

  var location = preload("res://location.tscn")

The above is just a 2d node with a sprite as a child
Then in my function below:

func setup_board():
    for x in range(boardWidth):
        var locationNode = location.instance()
        get_node('pieces').add_child(locationNode)

I want to be able to then set the position of the most recently created locationNode before I loop again and create the next one.

As you can see it's been placed as a child of the 2DNode called pieces. It's in a loop, so in my example boardWidth = 5 and it will create 5 of them, with the following names:

location
@location@2    
@location@3
@location@4
@location@5

I tried various things and have been searching for some time but I keep getting errors. Does anyone know a way to set the location of the last added instance?

Thanks a tonne... Rob

in Engine by (810 points)
edited by

1 Answer

+4 votes
Best answer

This should work:

func setup_board():
    for x in range(boardWidth):
        var locationNode = location.instance()
        locationNode.set_pos(newPos)
        get_node('pieces').add_child(locationNode)
by (478 points)
selected by

Thank you!

My mistake in all my attempts was as such:

locationNode.set_pos(xPos, yPos)

It would give an error, stating:

Invalid call to function 'set_pos' in base 'Node2D'. Expected 1 arguments.

I had to put in a simple Vector2 call!!!! OMG.

So it is now, for future reference for others needing help:

func setup_board():
    for x in range(boardWidth):
        board.append([])
        board[x]=[]

        var locationNode = location.instance()
        locationNode.set_pos(Vector2(xPos,yPos))
        get_node('pieces').add_child(locationNode)
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.

Categories