This is indeed a rather difficult problem to solve, even for advanced coders.
It seems like the character is moving past the mouse position and then quickly has to compensate.
Depending on the situation, different fixes might be adequate.
If your game is rather slow paced, with the character no requiring ultra precise movement, a nice fix would be to limit the velocity by a factor inversely proportional to the distance from the mouse. This would make them slow down, the closer they get to the mouse.
for this, replace
velocity = (direction * speed)
with
var length = direction.length()
if length < 150: velocity = direction*speed * (length/150)
else: velocity = direction*speed
If this is more like a high paced shooter situation where precision matters, maybe go for a direct position changing movement, instead of a physics based one
or implement a way to limit the ammount of degrees the character can turn with
extends CharacterBody2D
var speed = 200
var mouse_position = null
func ready():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _physics_process(_delta):
var force_vector = velocity.angle()
velocity = Vector2(0,0)
mouse_position = get_global_mouse_position()
if Input.is_action_pressed("MOUSE"):
var direction = (mouse_position - position).normalized()
velocity = (direction * speed)
var angle_difference = velocity.angle()-force_vector
if abs(angle_difference) > PI:
# vel = reset velocity angle and rotate it to the limiting factor
velocity = velocity.rotated(-velocity.angle()).rotated(-sign(angle_difference)*PI+velocity.angle())
move_and_slide()
The way this works is by taking the previous angle of movement and comparing it to the new one. If the difference is larger than 90 degrees in radians (i.e. PI), the angle is set to PI, so it is slowed down. If this is still to fast try changing both PI to sth like 2.0 or 1.5 (PI is 3.14).
Im actually not quite sure I got the math right, since I didnt test it, but try playing around with (sign(angle_difference)*PI to get it to work as you want.
This would probably result in them running in a circle around the mouse when they get there.
Good luck with your further coding journey 