How do I get bullets to shoot out of my gun in my Godot2D platformer?

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

Ok, so here is what my nodes look like right now:

KinematicBody (player)
     sprite
     collisonshape2D
     sprite (GUN)
           timer

Bullet.tscn is a separate scene with code that says:

extends KinematicBody2D
func _physics_process(delta):
    position.x += 10 

Right now, I have a script in the Gun that says:

extends Sprite

var Bullet = preload("res://Bullet.tscn") 

func shoot():
    var bullet = Bullet.instance()
    add_child(bullet)

func _process(delta):
    if Input.is_action_pressed("click"):
	    shoot()

The bullets spawn and move, but when I move forward, the bullets move forward faster, like they’ve been boosted. When I move backwards, the bullets stop and slightly move backwards until I stop moving. Can someone please explain how to fix this problem?

:bust_in_silhouette: Reply From: jgodfrey

So, the main problem is that you’re adding the newly spawned bullet as a child of the Gun, which in turn, is a child of the Player. So, any motion applied to the Player, will also be applied to the Gun (expected) and the spawned bullet (not expected).

You need to add the bullet as a child to some other object that’s not moving in your game. You could simply add the bullet as a child of your game world, or some other stationary container in your game world.

Bottom line, don’t add into the hierarchy of the Player itself or it will move with the player.

Thank you so much!

ZacurniaTate | 2020-08-09 21:54

:bust_in_silhouette: Reply From: ccmalachite

you can use “set_as_toplevel(true)” within the ready function of your bullet in order to separate the bullets movement from the players.