如何在Godot 4中使用move_and_slide移动物体到目标点并停止
在Godot 4中使用move_and_slide实现物体向目标移动并到达后停止
核心逻辑
通过计算物体与目标的距离,判断是否进入停止阈值范围,未到达时生成移动方向并调用move_and_slide,到达后重置速度停止移动。以下是具体实现步骤:
- 定义基础变量
在你的运动节点(如KinematicBody2D或KinematicBody3D)中添加可配置变量,方便调试和场景适配:
@export var target_position: Vector2 # 3D场景替换为Vector3 @export var move_speed: float = 200.0 @export var stop_threshold: float = 10.0 # 距离目标小于此值时停止
- 实现移动与停止逻辑
在_physics_process函数中处理核心逻辑(这是Godot处理物理运动的正确时机):
func _physics_process(delta: float) -> void: # 计算当前位置到目标的向量与距离 var to_target = target_position - global_position var distance_to_target = to_target.length() # 到达停止阈值,停止移动 if distance_to_target <= stop_threshold: velocity = Vector2.ZERO # 3D场景替换为Vector3.ZERO move_and_slide() # 调用一次更新物理状态 return # 未到达目标,计算移动方向并执行移动 var move_direction = to_target.normalized() velocity = move_direction * move_speed move_and_slide()
可选优化
- 平滑减速:如果需要物体接近目标时逐渐减速,替换速度计算部分为:
# 根据剩余距离动态调整速度,实现平滑减速 var adjusted_speed = move_speed * min(distance_to_target / stop_threshold, 1.0) velocity = move_direction * adjusted_speed - 避免抖动:如果物体在目标附近轻微抖动,可适当增大
stop_threshold,或者在停止后直接将物体位置对齐目标:if distance_to_target <= stop_threshold: global_position = target_position velocity = Vector2.ZERO move_and_slide() return - 动态目标适配:如果目标位置会动态变化(比如跟随其他物体),只需实时更新
target_position变量,上述逻辑会自动适配。
内容的提问来源于stack exchange,提问作者Positronium
相关产品推荐
相关产品推荐

