How to get target to move in direction of mouse?

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

Looking at the Godot documentation, I found a code to move towards mouse click:

func _physics_process(delta):
velocity = global_position.direction_to(target) * speed
if global_position.distance_to(target) > 5:
	velocity = move_and_slide(velocity)

I’m stuck on how to get the object to continuously move in that direction. Like if I click somewhere to the right of the player, I want the player to have constant velocity towards where I clicked and not stop. Any suggestions? Thank you!

:bust_in_silhouette: Reply From: ponponyaya

You may set the target when mouse click.

Like this following:

var target = Vector2.ZERO

func _physics_process(delta):
	if Input.is_mouse_button_pressed(1): # when click Left mouse button
		target = get_global_mouse_position()
	velocity = global_position.direction_to(target) * speed
	if global_position.distance_to(target) > 5:
		velocity = move_and_slide(velocity)