Unity3D-----摄像机镜头移动并限制角度

摄像机镜头跟随鼠标移动,并限制上下左右的移动角度

public class ViewFromCream : MonoBehaviour 
{
    public int speed=5;
    public Vector3 vect;
    
    private float xcream;
    private float ycream;

    public void Update()
    {
        CreamView();
    }

    private void CreamView()
    {
        float x = Input.GetAxis("Mouse X");
        float y = Input.GetAxis("Mouse Y");
        if (x!=0||y!=0)
        {
            LimitAngle(60);
            LimitAngleUandD(60);
            this.transform.Rotate(-y * speed, 0, 0);
            this.transform.Rotate(0, x * speed, 0, Space.World);
        }
    }

    /// <summary>
    /// 限制相机左右视角的角度
    /// </summary>
    /// <param name="angle">角度</param>
    private void LimitAngle(float angle)
    {
        vect = this.transform.eulerAngles;
        //当前相机x轴旋转的角度(0~360)
        xcream = IsPosNum(vect.x);       
        if (xcream > angle)
            this.transform.rotation = Quaternion.Euler(angle,vect.y,0);
        else if (xcream < -angle)
            this.transform.rotation = Quaternion.Euler(-angle, vect.y, 0);
    }
    /// <summary>
    /// 限制相机上下视角的角度
    /// </summary>
    /// <param name="angle"></param>
    private void LimitAngleUandD(float angle)
    {
        vect = this.transform.eulerAngles;
        //当前相机y轴旋转的角度(0~360)
        ycream = IsPosNum(vect.y);
        if (ycream > angle)
            this.transform.rotation = Quaternion.Euler(vect.x, angle, 0);
        else if (ycream < -angle)
            this.transform.rotation = Quaternion.Euler(vect.x, -angle, 0);
    }
    /// <summary>
    /// 将角度转换为-180~180的角度
    /// </summary>
    /// <param name="x"></param>
    /// <returns></returns>
    private float IsPosNum(float x)
    {
        x -= 180;
        if (x < 0)
            return x + 180;
        else return x - 180;      
    }
}
  • 对IsPosNum方法进行说明
    之所以要将获取的欧拉角转换为-180°-180°之间,是因为在获取eulerAngle中,x轴和y轴的值只有0-360,而没有负数,那么这将会复杂化我们角度的判断,如限制左右角度为-60-60之间,那么我们就要判断角度是否超过300度或是超过60度, 显然超过300度的角度必定超过60度,那么就需要另外加条件进行判断;因此对获取的值进行转化更为方便!
原创文章 3 获赞 2 访问量 167

猜你喜欢

转载自blog.csdn.net/Studious_S/article/details/106100540