i don't know how to set position for Node instance in GDNative C ++

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

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)

:bust_in_silhouette: Reply From: sash-rc

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).

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 *

F0remNKB | 2021-08-22 17:56

use Object::cast_to():

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

sash-rc | 2021-08-22 18:33

Thank you very much, everything works

F0remNKB | 2021-08-22 20:35