You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity相机平滑旋转移动异常:0°转359°时出现360°绕转问题

解决Unity相机跟随旋转时的360°绕圈问题

你的问题出在**直接对欧拉角(eulerAngles)做线性插值(Lerp)**上。欧拉角用三个数值表示旋转,0°和359°在数值上相差359,但实际角度只差1°。Vector3.Lerp只会按数值大小插值,所以会选择绕360°的长路径,而非向左的短路径。

解决方案:用四元数(Quaternion)处理旋转插值

四元数天生能处理旋转的周期性,会自动计算两个旋转之间的最短路径。修改你的旋转逻辑如下:

using UnityEngine;

public class CameraFollow : MonoBehaviour {

    public Transform target;

    public float smoothingspeed_movement = 0.125f;
    public float smoothingspeed_rotation= 0.5f;
    // 拆分偏移为位置和旋转偏移,逻辑更清晰
    public Vector3 positionOffset;
    public Vector3 rotationOffset;

    void FixedUpdate ()
    {
        // 平滑处理位置
        Vector3 desiredPosition = target.position + positionOffset;
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothingspeed_movement);
        transform.position = smoothedPosition;
        
        // 用四元数处理旋转,自动选择最短路径
        Quaternion desiredRotation = target.rotation * Quaternion.Euler(rotationOffset);
        // Lerp适合短距离旋转,Slerp适合长距离旋转,效果更自然
        Quaternion smoothedRotation = Quaternion.Lerp(transform.rotation, desiredRotation, smoothingspeed_rotation);
        transform.rotation = smoothedRotation;
    }
}

关键改动说明:

  1. 把原有的offset拆分为positionOffset和rotationOffset,避免位置与旋转偏移逻辑混淆。
  2. 旋转部分不再操作欧拉角,改用Quaternion.Lerp直接对四元数插值,自动解决0°到359°的短路径问题。
  3. 目标旋转计算为target.rotation * Quaternion.Euler(rotationOffset),确保旋转偏移是相对目标的局部旋转,而非全局欧拉角相加,避免万向锁等问题。

如果你坚持用欧拉角处理,也可以用Mathf.DeltaAngle计算最短角度差值再过渡(以Y轴为例):

float currentY = transform.eulerAngles.y;
float targetY = target.eulerAngles.y + rotationOffset.y;
// DeltaAngle返回两个角度的最短差值(范围-180到180)
float angleDelta = Mathf.DeltaAngle(currentY, targetY);
float smoothedY = currentY + angleDelta * smoothingspeed_rotation;
transform.eulerAngles = new Vector3(transform.eulerAngles.x, smoothedY, transform.eulerAngles.z);

这种方式需要单独处理每个旋转轴,适合仅控制单轴旋转的场景。

内容的提问来源于stack exchange,提问作者Lulu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:48:18