Trouble with getting Player to mouse position after left click release

4.3 Godot Version

Hi there. I’m trying to create a player movement system with a mouse where the player follows the mouse and stops when left-click.

Then, when you press down on the left_click button and hold it there, at left_click button release, the player will travel to the spot where the left_click button was released. Think of it like a drag and drop but with the player instead.

I managed to accomplish this somewhat, however when I release the left click, the player only moves a few pixels towards the position where i released the left_click button and not go to that actual position. Does anyone know what may be my problem?

Here is my code:

extends CharacterBody2D

@export var speed = 200
var mouse_position = null
var release_position = Vector2()
var is_moving_enabled = false

func _ready():
	mouse_position = position


func _physics_process(delta):
	if is_moving_enabled:
		mouse_position = get_global_mouse_position()
		var direction = (mouse_position - position).normalized()
		velocity = (direction * speed)
		move_and_slide()
		look_at(mouse_position)
	else:
		velocity = Vector2(0,0)
	

			
func _input(event):
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			print("left click")
			is_moving_enabled = !is_moving_enabled
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		if event.pressed:
			print("left click held")
		else:
			print("left click release")
			release_position = get_global_mouse_position()
			if position.distance_to(release_position) > 3:
				var direction = (release_position - position).normalized()
				velocity = (direction * speed)
				move_and_slide()

Maybe would be cleaner as a state machine. First state is following, 2nd state is goto click and back to stop state.

extends CharacterBody2D

@export var speed = 200
var mouse_position = Vector2.ZERO
var release_position = Vector2.ZERO
enum state {STOP=0, FOLLOW, GOTO}
var is_moving_state : int = state.STOP 

func _physics_process(delta):
	match is_moving_state:
		state.STOP :
			pass
		state.FOLLOW :
			mouse_position = get_global_mouse_position()
			var direction = (mouse_position - position).normalized()
			velocity = (direction * speed)
			move_and_slide()
		state.GOTO:
			if position.distance_to(release_position) > 3:
				move_and_slide()
			else:
				is_moving_state = state.STOP	
		
func _input(event):
	if event is InputEventMouseButton:
		if event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
			match is_moving_state:
				state.STOP: # Click 1
					print("FOLLOW")
					is_moving_state= state.FOLLOW

				state.FOLLOW: ## Click 2
					print("GOTO")
					is_moving_state= state.GOTO
					release_position=get_global_mouse_position()