摄像机旋转约束问题及解决

去年2月份写过一个旋转约束的解决方法,不过是硬算的,今天无意中在论坛发现了一个解决方法

if (euler.x > 180) euler.x -= 360;
if (euler.x < -180) euler.x += 360;

这样就可以保证旋转区间可比较

具体代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestCamera : MonoBehaviour
{
    public Transform target;
    public Vector2 xLimit;
    public Vector2 yLimit;
    public Vector2 zLimit;


    void LateUpdate()
    {
        transform.LookAt(target);

        var euler = FixEuler(transform.eulerAngles);

        euler.x = Mathf.Clamp(euler.x, xLimit.x, xLimit.y);
        euler.y = Mathf.Clamp(euler.y, yLimit.x, yLimit.y);
        euler.z = Mathf.Clamp(euler.z, zLimit.x, zLimit.y);

        transform.eulerAngles = euler;
    }

    Vector3 FixEuler(Vector3 euler)
    {
        if (euler.x > 180) euler.x -= 360;
        if (euler.x < -180) euler.x += 360;

        if (euler.y > 180) euler.y -= 360;
        if (euler.y < -180) euler.y += 360;

        if (euler.z > 180) euler.z -= 360;
        if (euler.z < -180) euler.z += 360;

        return euler;
    }
}
View Code
原文地址:https://www.cnblogs.com/hont/p/6657941.html