Need Help With Instantiate

Godot Version

4.3

Question

I am attempting to instantiate a bullet, point it in the direction of the mouse and move it forward. When I run the game it works fine until I start moving the character. The bullets start shooting in directions away from the mouse and eventually dont even rotate at all.

Here is the player code:

extends CharacterBody2D

var bullet = preload("res://Scenes/bullet.tscn")
var MOVESPEED = 5

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if Input.is_action_pressed("up"):
		velocity.y -= MOVESPEED
	if Input.is_action_pressed("down"):
		velocity.y += MOVESPEED
	if Input.is_action_pressed("right"):
		velocity.x += MOVESPEED
	if Input.is_action_pressed("left"):
		velocity.x -= MOVESPEED
	
	if Input.is_action_just_pressed("shoot"):
		var instance = bullet.instantiate()
		instance.look_at(get_global_mouse_position())
		add_child(instance)
	
	move_and_slide()

Bullet code:

extends CharacterBody2D

@onready var collider = $CollisionShape2D

var MOVESPEED = 10

func _ready() -> void:
	position += transform.x * 25
	
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	position += transform.x * MOVESPEED

move look_at to after add_child. nodes have… issues, when altering properties before being in the scene tree.

if Input.is_action_just_pressed("shoot"):
		var instance = bullet.instantiate()
		add_child(instance)
		instance.look_at(get_global_mouse_position())

Thanks! This didn’t work exactly correct but because of your advice i changed where it rotated to the mouse and it’s working fine now.

New code (bullet):

extends CharacterBody2D

@onready var collider = $CollisionShape2D

var MOVESPEED = 10

func _ready() -> void:
	look_at(get_global_mouse_position())
	position += transform.x * 25
	
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	position += transform.x * MOVESPEED