Instanciate a character next to another character

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

Hey there.

I’ve got a character, and I can spawn his ghost if some conditions are met.
My code is the following:

var ghostScene = load("res://Scenes/Ghost.tscn")
var ghostInstance = ghostScene.instance()
ghostInstance.position = Vector2(position.x+32, position.y)

It’s just for test purpose here and there’s something I can’t understand. If I only do add_child(ghostInstance) and do nothing about the position, the ghost will spawn as expected but will follow player’s movement when inputting something (I can understand it since ghost would be a child of my character).

So my question is simple: why isn’t it working when I try to instanciate the ghost at the same level as the hero? I mean, the print gives me the expected result, but right after if I try to check the position again, the node doesn’t exist anymore. If I let the ghost as a hero’s child, the instance isn’t deleted… Why?

:bust_in_silhouette: Reply From: Socrates

I’m not entirely clear what you’re trying to do, but i think the Platformer2d demo might be worth looking at. Bullets are instantiated in a similar way there. You might want:


You can also do:

var ghostInstance = preload("res://Scenes/Ghost.tscn").instance()

Also be aware that position is the position relative to the parent and global_position is the position relative to the root.

My issue is that when I instanciate it as a child (with addChild alone) it works well but since the position is relative, the ghost moves when the player moves which isn’t what I want. Then I’m using get_parent().add_child(…) instead, but the instance only seem to be active one frame and then I can’t find it anymore…

At least I can’t see it and the line print(get_node(“…/Ghost”).position) says there’s no such node (despite the fact I instanciated it with this name just before)

EDIT: just saw that I have a message
“Parent node is busy setting up children, add_node() failed”
I gotta figure why. It’s weird since I can still set and display its position

Yozamu | 2018-04-07 18:59

Did you try using preload instead of load?

Socrates | 2018-04-07 19:38

I tried preload, didn’t work.
However, I replaced get_parent().add_child(ghostInstance) by
get_parent().call_deferred(“add_child”, ghostInstance)

And it works. But I don’t really know the technical reasons which explain both situations.

Yozamu | 2018-04-07 19:55