0 votes

So, I am making a Galaga clone, and am trying to figure out the system for making the player shoot bullets.

Player scene tree:
-Area2d(named Player)
- CollisionShape2D
- Sprite
- Bullet(scene)

Bullet scene tree:
- Area2D(named Bullet)
- Sprite
- CollisionShape2D
- VisibilityNotifier2D

Here is my code for the player:

extends Area2D

signal onBulletSpawn

var Bullet = preload("res://Bullet.tscn")
export (NodePath) var target_node_nodepath = null
var target_node
export var playerSpeed = 400
var screen_size

func _ready():
    screen_size = get_viewport_rect().size

func _process(delta):
    var Playervelocity = Vector2()
    if Input.is_action_pressed("ui_right"):
        Playervelocity.x += 1
    if Input.is_action_pressed("ui_left"):
        Playervelocity.x -= 1
    if Input.is_action_just_pressed("ui_select"):
        var bullet = Bullet.instance()
        bullet.position = position
    position += Playervelocity * delta * playerSpeed
    position.x = clamp(position.x, 0, screen_size.x)

Here is my code for the bullet:

extends Area2D

export var bulletSpeed = -10000

func _on_VisibilityNotifier2D_screen_exited():

func _process(delta):
    position += Vector2(0.0, bulletSpeed * delta)

So this all works fine, but when when I shoot a bullet, then move my character, the bullet moves with the character.... Any suggestions on how to fix this?

in Engine by (20 points)

2 Answers

+1 vote
Best answer

You're adding the bullet as the child of the player, so naturally it's going to move with the player.

Instead, you should add your bullets to the world. This could be as simple as get_parent().add_child(bullet), or you can use get_node() to use whichever node you want to hold the bullets.

by (21,942 points)
selected by

You both are the best answer.... lol thnx!

+1 vote


It's because the bullet is a child of the character. You need to add the bullet to the parent scene, like this:

by (2,047 points)

Thnx for the answer!

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 [email protected] with your username.