How to create and destroy an object in GD script?

Godot Version

Godot v4.7.2

Question

I’ve recently got started with game development in Godot. I’m currently trying to create bullets when the player left clicks

Currently I have this to send the in the direction of the mouse position:

func _process(delta):
	if fired == true:
		if Input.is_action_just_pressed("mouse_left"):
			mouse_pos = get_global_mouse_position()
			angle = get_angle_to(mouse_pos)
			
			#go to player position
			#un-queue_free()
			
			look_at(get_global_mouse_position())
			velocity.x = cos(angle)
			velocity.y = sin(angle)

			timer.start()
			fired = true
			print("Fired")
	else:
		print("Already fired")

func _physics_process(delta: float) -> void:
	if fired == true:
		global_position += velocity * speed * delta

func _on_timer_timeout() -> void:
	fired = false
	print(get_global_transform())
	queue_free()

EDIT – The code above is in my bullet scene

However, I’m not sure as to how to get the player position an go to it (presumably position), and if you can undo the queue_free?

Sorry if this doesn’t make the most sense, I’m new to game development so may be missing something but thanks for your help

What is this script? Your bullet? Your player?

On your player script you can instantiate scenes, such as the bullet and provide information like direction/velocity

# player.gd

const BULLET_SCENE: String = "res://bullet.tscn"

func _unhandled_input(event: InputEvent) -> void:
    if event.is_action_pressed("Fire"):
        var new_bullet: Node2D = load(BULLET_SCENE).instantiate()
        new_bullet.velocity = global_position.direction_to(get_global_mouse_position()) * bullet_speed
        new_bullet.position = position
        new_bullet.rotation = rotation
        add_sibling(new_bullet)

Check out the official Godot tutorial

I’m not entirely sure I follow what you’re trying to achieve.

I assume you want a projectile to travel in the direction from the player’s position toward the point where the mouse was clicked.

Since the player is the one firing, the check for a mouse click should happen within the player’s _process method, not the bullet’s.

By handling this in the player script, you have access to both the player’s position and the click coordinates. Subtracting one from the other gives you the direction vector for the bullet—it’s standard practice to normalize this into a unit vector.

The bullet shouldn’t be a child of the player; if it were, it would move along with the player. It makes more sense to have the level (or the current scene) add the bullet as a child, passing the direction vector to it (gertkeno’s approach is much better).

You instantiate a bullet and assign the direction vector to it.

The bullet simply keeps moving until it either collides with something or leaves the screen (Godot provides built-in components to detect this). At that point, you call queue_free() to remove it entirely.

Bullets aren’t reused; you simply create as many as needed.

I don’t quite understand the timer in your code.

A timer would make sense on the player side, as weapons typically have a specific fire rate—that’s a perfect use case for a timer.

I hope this helps!

Sorry, yes, should have clarified. This script is in my bullet scene. I tried fitting your code into my player’s script, but should the “rest://bullet.tscn” just work? (my bullet scene is called that), erros are saying

player.gd:17 @ get_input(): Cannot open file 'res://bullet.tscn'.
player.gd:17 @ get_input(): Failed loading resource 'res://bullet.tscn'.
get_input: Attempt to call function 'instantiate' in base 'null instance' on a null instance.

My player script now is:

const SPEED = 1000
const BULLET_SCENE: String = "res://bullet.tscn"
const bullet_speed = 1000
var health = 100
var mouse_pos
var rotation_direction


	
func get_input():
	var input_direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	velocity = input_direction * SPEED
	if Input.is_action_pressed("mouse_left"):
		var new_bullet: Node2D = load(BULLET_SCENE).instantiate()
		new_bullet.velocity = global_position.direction_to(get_global_mouse_position()) * bullet_speed
		new_bullet.position = position
		new_bullet.rotation = rotation
		add_sibling(new_bullet)


func _physics_process(delta: float) -> void:
	mouse_pos = get_local_mouse_position()
	look_at(get_global_mouse_position())
	
	get_input()
	move_and_slide()
	

Is it the referencing that’s the error or what? Thanks

Thanks for your reply, how would I instantiate it? As for the timer, that was an attempt to delete the bullet a short time after it has been fired, though of course I couldn’t get it back once deleted.

I don’t think BULLET_SCENE should be a String; it should probably be a PackedScene. With the player script open, select the bullet scene, hold down the Ctrl key, and drag it into the player script. This will allow Godot to correctly generate the path to your scenek, likely in a format such as const BULLET_SCENE = preload(“uid://rta7q842acnw”) (using a UID) or a path similar to the one you’ve shown.

I think that it is better to use preload rather than calling load every single time. Change var new_bullet: Node2D = load(BULLET_SCENE).instantiate() to var new_bullet: Node2D = BULLET_SCENE.instantiate().

Additionally, it would be better to use Input.is_action_just_pressed(“mouse_left”). This ensures that only one bullet is fired, rather than spawning a new one during every _physics_process call while the left mouse button is held down.

I think the logical approach is to remove the bullet when it collides with something or leaves the screen, rather than based on time. To detect when it leaves the screen, add a VisibleOnScreenNotifier2D and listen for its signal to trigger queue_free(). I believe the tutorial gertkeno pointed you toward includes an example of this.

Thanks, now it’s spawning. Just one final thing: how do I then get movement working?

I’ve just thought I could do:

func _on_ready() -> void:
	mouse_pos = get_global_mouse_position()
	angle = get_angle_to(mouse_pos)
	look_at(get_global_mouse_position())
	velocity.x = cos(angle)
	velocity.y = sin(angle)

However all it does is set the angle, which I guess is the first step but the velocity isn’t working

What I would do is give the bullet a variable direction. When you create it, from the player, you do: bullet.direction = global_position.direction_to(get_global_mouse_position()).normalized()

Then, in the bullet’s _physics_process (not in _ready), you do: global_position += direction * SPEED * delta