

extends CharacterBody2D
@export var speed = 400
var target = position
func _input(event):
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
target = get_global_mouse_position()
func _physics_process(delta):
velocity = position.direction_to(target) * speed
if position.distance_to(target) > 10:
move_and_slide()
注意我们在移动之前做的 distance_to()
检查. 如果没有这个检查, 物体在到达目标位置时会 "抖动", 因为它稍微移过该位置时就会试图向后移动, 只是每次移动步长都会有点远从而导致来回重复移动.
如果你喜欢, 取消注释的 rotation
代码可以使物体转向其运动方向.