Attention | Topic was automatically imported from the old Question2Answer platform. | |
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)
|_CollsionShape2D
|_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)
|_CollsionShape2D
|_Sprite
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
$Sprite.look_at(direction)
func _physics_process(delta):
momentum = momentum.move_toward(new_direction, velocity * delta)
move_and_slide(momentum)
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
get_parent().get_parent().get_node("Projectiles").add_child(Bullet_Istance)
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?