0 votes

here is my code to explain
in .h

Position2D * mgpos;
Ref <PackedScene> MAGIC_BLAST;
Node * magic_blast;

in .cpp

void Player :: _ ready () {
    ResourceLoader * loader = ResourceLoader :: get_singleton ();
    MAGIC_BLAST = loader-> load ("res: //Nodes/Player/Magic/Magic_Blast.tscn", "PackedScene");
    mgpos = get_node <Position2D> (NodePath ("Position2D"));

void Player :: Fire () {
    if (i-> is_action_pressed ("ui_attack")) {
    get_parent () -> add_child (magic_blast);
    magic_blast-> set_position // <<< - ??? not work
void Player :: _ physics_process (float delta) {
    magic_blast = MAGIC_BLAST-> instance ();


I apologize if I have bad code, but I'm just practicing writing it and doing a little project,
the problem is that I cannot set the position for magic_blast(instaced)

Godot version v3.3.2
in Engine by (29 points)

1 Answer

+1 vote
Best answer

First: you're instancing node in _ physics_process: this is wrong, as this code is called 60 time/sec, spawning orphan instances.
It should be done in void Player :: Fire (), just before add_child(). Otherwise you'll get memory leak.

Second: you defined a single variable magic_blast, and (even being placed into void Player :: Fire ()) you're reassigning it with each new instance.
It should be either local variable, array of instances or guarded instance/singleton. With proper cleanup. Or again: memory leak.

Third: to use set_position() you should declare magic_blast as Node2D, Sprite, or whatever type it actually is, but not just Node (which is generic and does not have such function).

by (1,646 points)
selected by

but there is a problem if you do Node2D * magic_blast = MAGIC_BLAST-> instance ();
then it gives an error value of type "godot :: Node *" cannot be used to initialize an entity of type "godot :: Node2D *

use Object::cast_to():

Node2D * magic_blast = cast_to<Node2D>( MAGIC_BLAST->instance() );

Thank you very much, everything works

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.