Help with add_child()

Godot Version

4.2.1

Question

I am very new to this engine and programming in general,
I am trying to make so that bullets can fire out indefinitely but my script can only shoot one bullet only
My script:

extends Sprite2D

@onready var n = load(“res://bullet.tscn”).instantiate()

func _ready():
pass

func _physics_process(_delta):
look_at(get_global_mouse_position())
if Input.is_action_just_pressed(“ui_mouse”):
self.get_parent().add_child(n)

you need to create a new instance when you push the button

if(Input.is_action_just_pressed("ui_mouse")):
    var bullet = n.instance() # here you create a new bullet
    # you can now work with bullet  with code as it is a normal object in your level
    get_parent.add(n)

oh by the way . dont forget to destroy your bullet when its leaves the screen.
There is VisibleOnScreenNotifier2D node for this. (Keyword signals)

1 Like

Thanks for the help but, the game keeps crashing(?) Did I do the code right?

extends Sprite2D

@onready var n = load(“res://bullet.tscn”).instantiate()

func _ready():
pass

func _physics_process(_delta):
look_at(get_global_mouse_position())
if(Input.is_action_just_pressed(“ui_mouse”)):
var bullet = n.instance() # here you create a new bullet
var speed = 100
transform.x += get_parent().transform.x * speed * _delta
transform.y += get_parent().transform.y * speed * _delta
# you can now work with bullet with code as it is a normal object in your level
get_parent().add_child(n)

remove the instatiate from load like

@onready var n = preload(“res://bullet.tscn”)

and here you create a new instance
var bullet = n.instantiate()

1 Like

It works! thank you so much

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.