unity中获得inspector面板rotation的值

目录

前言:

一、inspector的rotation的值代码实现

二、结果验证


前言:

在unity编辑器有时候要根据inpsector的rotation的值来做设定,比如限定摄像机的的旋转角度,控制rotation.x在一定的范围内。但是实际情况中inpsector的面板值是经过转换的值,需要通过eulerAngle欧拉值计算才能获得。这里实现通过transform的eulerAngle获得inspector的rotation面板值

一、inspector的rotation的值代码实现

rotation.x具体实现是需要GameObject的trasnform.up与原始Vector.up的dot值来判断 

     /// <summary>
        /// 欧拉角转换Instector的rotation值
        /// </summary>
        /// <param name="up"> GameObject 的transform.up</param>
        /// <param name="eulerAngle">GameObject 的transform.eulerAngle</param>
        /// <returns> 返回已经转换的值</returns>

        private Vector3 EulerAngles2InspectorRotation(Vector3 up, Vector3 eulerAngle)
        {

            Vector3 resVector = eulerAngle;

            if (Vector3.Dot(up, Vector3.up) >= 0f)
            {
                if (eulerAngle.x >= 0f && eulerAngle.x <= 90f)
                    resVector.x = eulerAngle.x;

                if (eulerAngle.x >= 270f && eulerAngle.x <= 360f)
                    resVector.x = eulerAngle.x - 360f;
            }

            if (Vector3.Dot(up, Vector3.up) < 0f)
            {
                if (eulerAngle.x >= 0f && eulerAngle.x <= 90f)
                    resVector.x = 180 - eulerAngle.x;

                if (eulerAngle.x >= 270f && eulerAngle.x <= 360f)
                    resVector.x = 180 - eulerAngle.x;
            }

            if (eulerAngle.y > 180)
                resVector.y = eulerAngle.y - 360f;

            if (eulerAngle.z > 180)
                resVector.z = eulerAngle.z - 360f;


            Debug.Log(" Inspector Rotation: " + " x=" + to2Precision(resVector.x) + " , y=" + to2Precision(resVector.y) + " , z=" + to2Precision(resVector.z));

            return resVector;
        }

        /// <summary>
        /// 取小数点三位精度
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private string to2Precision(float value)
        {
            float v = Mathf.RoundToInt(value * 1000);

            return (v / 1000f).ToString();

        }

1)调用实现

Vector3 rotation =  EulerAngles2InspectorRotation(transform.up, transform.eulerAngles);

2)rotation转换回eulerAngles角度

 Vector3 v = Quaternion.Euler(rotation).eulerAngles;

二、结果验证

 

猜你喜欢

转载自blog.csdn.net/lejian/article/details/130089325