Making player bullet's direction lerps back towards player

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By KurtBlissZ

I’m trying to make a gun that shoot a bullet that slowly turns back towards the player… But it only seems to get stuck in one spot with it direction spinning around “randomly” I tried a bunch of things but haven’t had much luck… suggestions? I mostly curious on how I can lerp its angle specifically… but as an alternative I think I could just have a vector that slowly move towards the player maybe…

Shooting code:

if Input.is_action_just_pressed("shoot") and has_gun:
	var inst : Bullet = ld_bullet.instance()
	inst.dir = rotation
	inst.spawn_pos = muzzle.global_position
	add_child(inst)

Bullet code:

class_name Bullet
extends Area2D
var spawn_pos
var dir = 0 
var target_player = false

func _ready():
	print(dir)
	set_as_toplevel(true)
	global_position = spawn_pos

func _process(delta):
	if target_player:
		var dir_to_player = global_position.angle_to(Master.player.global_position)
		dir = lerp_angle(dir, dir_to_player, 1)
		print("lerp ", dir)
	var motion = Vector2(5,0).rotated(dir)
	position += motion

func _on_TimerTurn_timeout():
	target_player = true

thanks for reading (:

:bust_in_silhouette: Reply From: ClumsyDog

Here’s what I think will work but haven’t tested:

extends Area2D
class_name Bullet

var spawn_pos
var dir = 0 
var target_player = false

var speed = 500
var velocity = Vector2.ZERO

func _ready():
    print(dir)
    set_as_toplevel(true)
    global_position = spawn_pos

func _process(delta):
    # rotate towards velocity, independent of movement
    rotation = lerp_angle(rotation, velocity.angle(), 0.3)

func _physics_process(delta):
    if target_player:
        var dir_to_player = global_position.direction_to(Master.player.global_position)
        velocity = dir_to_player * speed
    
    # move bullet
    global_position += velocity * delta

func _on_TimerTurn_timeout():
    target_player = true