0 votes

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?

Godot version 3.2.2.stable.official
in Engine by (12 points)

1 Answer

0 votes

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.

by (625 points)
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 webmaster@godotengine.org with your username.