0 votes

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.set_name("Ghost")
get_node("../").add_child(ghostInstance)
ghostInstance.position = Vector2(position.x+32, position.y)
print(ghostInstance.position)

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?

asked Apr 7, 2018 in Engine by Yozamu (14 points)

1 Answer

–1 vote

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:

get_parent().add_child(ghostInstance)

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.

answered Apr 7, 2018 by Socrates (552 points)

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 getparent().addchild(..) 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

Did you try using preload instead of load?

I tried preload, didn't work.
However, I replaced getparent().addchild(ghostInstance) by
getparent().calldeferred("add_child", ghostInstance)

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

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.