Godot4.2.2角色移动方向旋转不流畅问题求助
解决Godot角色朝移动方向平滑旋转的问题
你的问题出在直接硬赋值旋转,没有做过渡插值。下面是修改后的代码,实现平滑旋转同时避免异常旋转:
extends CharacterBody3D const NormalSpeed := 180 const SprintSpeed := 360 const SneakSpeed := 90 const fall_acce := 60 const jump_impulse := 1000 # 控制旋转平滑速度,值越大旋转越快 const RotationSpeed := 8.0 var target_velocity := Vector3.ZERO func _physics_process(delta): var direction := Vector3.ZERO if Input.is_action_pressed("m_forward"): direction.x += 1 if Input.is_action_pressed("m_backward"): direction.x -= 1 if Input.is_action_pressed("m_left"): direction.z -= 1 if Input.is_action_pressed("m_right"): direction.z += 1 if direction != Vector3.ZERO: direction = direction.normalized() # 计算目标朝向的基准矩阵 var target_basis := Basis.looking_at(direction, Vector3.UP) # 用球面插值平滑过渡当前旋转到目标旋转 $Pivot.basis = $Pivot.basis.slerp(target_basis, RotationSpeed * delta) # 无输入时保持当前旋转,避免随机转动 if not is_on_floor(): target_velocity.y -= fall_acce * delta var speed := NormalSpeed if Input.is_action_pressed("m_sprint"): speed = SprintSpeed if Input.is_action_pressed("sneak"): $CollisionShape3D.disabled = true speed = SneakSpeed else: $CollisionShape3D.disabled = false if is_on_floor() and Input.is_action_just_pressed("jump"): target_velocity.y = jump_impulse * delta target_velocity.x = direction.x * speed * delta target_velocity.z = direction.z * speed * delta velocity = target_velocity move_and_slide()
关键修改说明:
- 新增
RotationSpeed参数,调整这个值可以控制旋转的平滑快慢,值越大旋转越灵敏,越小越缓慢。 - 用
basis.slerp()替代直接赋值,球面插值会在当前旋转和目标旋转之间做自然过渡,避免生硬跳转。 - 保留
direction.normalized()确保斜向移动时旋转方向精准。 - 移除无输入时的冗余操作,杜绝随机旋转问题。
如果仍出现持续旋转,检查Pivot节点的初始旋转是否正确,确保looking_at的向上方向参数Vector3.UP匹配你的场景坐标系。
内容的提问来源于stack exchange,提问作者Aluxus Alex
相关产品推荐
相关产品推荐

