How to implement correctly "Move to click" - the "stop in the destination" part?

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

I’m currently using a CharacterBody2D with a Camera2D that follows the Player around (the player is always shown at the center of the screen).
I successfully implemented the click and move logic, but I can’t make the player stop at the click destination.
How to do that?
Here is my code:

extends CharacterBody2D


@export var MAX_SPEED = 80
@export var ACCELERATION = 1500
@export var FRICTION = 1200
@onready var axis = Vector2.ZERO


@onready var animations = $AnimationPlayer

func _physics_process(delta):

func update_animation():
if velocity == Vector2.ZERO:“idle”)
var direction = get_direction(axis.normalized())“walk” + direction)

func move(delta):
if axis == Vector2.ZERO:
apply_friction(FRICTION * delta)
apply_movement(axis * ACCELERATION * delta)

func apply_friction(amount):
if velocity.length() > amount:
velocity -= velocity.normalized() * amount
velocity = Vector2.ZERO

func apply_movement(accel):
velocity += accel
velocity = velocity.limit_length(MAX_SPEED)

func get_direction(normalized_vec):
var directions = [“Up”, “Down”, “Left”, “Right”]
var dot_products = [,,,]
var max_index = 0
for i in range(1, 4):
if dot_products[i] > dot_products[max_index]:
max_index = i
return directions[max_index]

func _unhandled_input(event):
if event is InputEventMouseButton:
var target_position = event.position
var viewport_size = get_viewport_rect().size
var center = viewport_size / 2
axis = (target_position - center).normalized()

:bust_in_silhouette: Reply From: TRAILtheGREAT

Based on your existing movement code, I would suggest applying friction when the character is within a certain distance of the target point. This won’t be perfectly accurate and the less friction you apply when slowing down, the larger that circle of inaccuracy needs to be.

Another more complicated solution would be to do some physics calculations based your current speed and deceleration rate to figure out exactly when you should start slowing down. This would be more accurate but you might need to break out the pen and paper to figure out the correct algorithm.