I am working on a Bullet Hell Rougelite game, and I am trying to allow the player to shoot bullets. But every time I shoot it throws an error Invalid call. Nonexistent function ‘instance` in base ‘CharacterBody2D (bullet.gd)’
Player
|-Graphics
|-CollisionShape2D
|-Weapon
|-Bullet
|-Graphics
|-CollisionShape2D
weapon.gd
extends Node2D
@export var bullet_speed = 10000
signal shoot_bullet(speed)
func _ready():
$Bullet.visible = false
func _process(_delta):
look_at(get_global_mouse_position())
func shoot(speed):
print(“Shooting Speed: “ + str(speed))
var bullet_instance = $Bullet
bullet_instance.rotation = rotation
var instance = bullet_instance.instance()
add_child(instance)
$Bullet.visible = true
shoot_bullet.emit(bullet_speed)
func _input(_event):
if Input.is_action_just_pressed(“attack”):
shoot(bullet_speed)
@gertkeno thanks, but whenever I shoot it throws this error though (similar to the one I provided in the OP) → Invalid call. Nonexistent function ‘instantiate’ in base ‘CharacterBody2D (bullet.gd)’
@athousandships I know this would be not on topic, but when I shoot, it doesn’t face and move in the right way (the opposite way in fact), and the movement doesn’t repeat. How could I fix this?
You will want instantiate(), but you need to re-organize a couple things first.
Typically the bullet should not exist until fired, right click “Bullet” in the scene tree and select “Save Branch as Scene”, name it “Bullet.tscn”, then delete it from the Player’s scene. In your script you will reference and instantiate this new scene like so.
# weapon .gd
extends Node2D
const BULLET = preload("Bullet.tscn")
@export var bullet_speed = 10000
func shoot(speed):
var bullet_instance = BULLET.instantiate()
# adding as a child ment moving the player moves any bullets
# in flight too so we add child to the root instead
get_tree().root.add_child(instance)
The bullet only needs it’s _physics_process if we supply the rest of the information at instantiation.
func shoot(speed):
var bullet_instance = BULLET.instantiate()
bullet_instance.position = global_position
var brotation := (get_global_mouse_position() - global_position).angle()
bullet_instance.rotation = brotation # make negative if your image is facing left
bullet_instance.velocity = Vector2(bullet_speed, 0).rotated(brotation)
get_tree().root.add_child(instance)