How to make a projectile turn based on a maximum turn speed and a target's position

Godot Version

4.7.2

Question

I’m making a projectile system for my game, and I have the target selection working, but I can’t figure out how to make the projectile’s direction (a normalized Vector2) point towards its target (an Enemy, which extends CharacterBody2D).
Here’s the code I use to select my target and point the projectile in a direction (this function is connected to a Timer):

func _update_homing_target() -> void:
	if not resource.homing:
		return
	var valid_targets: Array[Enemy]
	for body in homing_range.get_overlapping_bodies():
		if body is Enemy:
			valid_targets.append(body)
	if resource.target == resource.HomingTargets.RANDOM and valid_targets.size() > 0:
		target = valid_targets.pick_random()
	elif resource.target == resource.HomingTargets.NEAREST:
		var distances: Dictionary[Enemy, float]
		for trgt in valid_targets:
			distances[trgt] = global_position.distance_to(trgt.global_position)
		if distances.size() > 0:
			var d := PackedFloat64Array(distances.values())
			d.sort()
			target = distances.find_key(d[0])
		else:
			target = null
	else:
		target = null
	if target != null:
		# i dont know how to make the projectile turn based on a max speed :(
		direction # projectile's direction
		resource.get_turn_speed(knockback) # max turn speed

On every frame:

  • get the wanted direction vector by subtracting target position and projectile position
  • calculate the angle between current direction vector and wanted direction vector using Vector2::angle_to()
  • rotate the projectile by turn_speed * delta * sign(angle_between_directions)
  • if the absolute value of the angle between is smaller than turn_speed * delta - rotate by angle between directions instead.