How to make a node child of another without modifying it's position

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

I don’t know if the title explains the problem but i don’t know how else to say it

So I have this node structure in my world scene

World (Node2D)
|_Projectiles (Node2D)
|_Player (KinematicBody2D)
    |_gun (sprite)

The gun has a script to move it around the player following the mouse, i wanted to add a shooting mechanic so i made a shoot function:

func shoot():
    var pos = get_global_transform().x.x
    var Bullet = preload("res://Bullet.tscn")
    var Bullet_Istance = Bullet.instance()
    Bullet_Istance.get_node("Projectile").direction = get_global_mouse_position()
    Bullet_Istance.position.x = pos + 20
    call_deferred("add_child", Bullet_Istance)

the structure of the Bullet scene is this
Projectile (Node2D)
|_Projectile (KinematicBody2D)

the Bullet KB2 has this script to move:

extends KinematicBody2D

var direction
var momentum = Vector2()
export var velocity = 50
var new_direction

func _ready():
    new_direction = direction

func _physics_process(delta):
    momentum = momentum.move_toward(new_direction, velocity * delta)

I was able to fix the bullet always pointing at the mouse after beeing launched by setting it in the ready functions, so only once, but the bullet still moves around weirdly when i move my cursor 'cause it’s parented to the gun, to fix it i wanted to parent it to the Projectiles Node but if i add this line of code


The bullet will spawn at the projectile node, therefore at the world origin on the top left corner

So my question is. am i approaching it the wrong way or is there something bad in the code?

:bust_in_silhouette: Reply From: MrEliptik

Your approach is correct, by adding the bullet to the projectiles node, it will be decoupled from your gun and thus won’t move when you move your mouse.
The problem is that when you add the bullet to the node, it’s position is 0 relative to its parent. Because your projectiles node hasn’t been moved, it’s in 0,0 so in the top left corner.
Try setting the global_position of your bullet instead of the position.