public Quaternion DirToQua(Vector3 dir) { //z==y x==z y==x float yawRad = Mathf.Atan2(dir.y, dir.x); float pitchRad = Mathf.Atan2(dir.z, Mathf.Sqrt(dir.x * dir.x + dir.y * dir.y)); float divide_by_2 = 0.5f; float sp, sy, cp, cy; SinCos(out sp, out cp, pitchRad * divide_by_2); SinCos(out sy, out cy, yawRad * divide_by_2); Quaternion rotationQuat; rotationQuat.x = sp * sy; rotationQuat.y = -sp * cy; rotationQuat.z = cp * sy; rotationQuat.w = cp * cy; return rotationQuat; } public void SinCos(out float scalarSin, out float scalarCos, float value) { float inv_pi = 0.31830988618f; float half_pi = 1.57079632679f; float quotient = (inv_pi * 0.5f) * value; if (value >= 0) { quotient = (float)((int)(quotient + 0.5f)); } else { quotient = (float)((int)(quotient - 0.5f)); } float y = value - (2.0f * Mathf.PI) * quotient; float sign; if (y > half_pi) { y = Mathf.PI - y; sign = -1.0f; } else if (y < -half_pi) { y = -Mathf.PI - y; sign = -1.0f; } else { sign = +1.0f; } float y2 = y * y; // 11-degree minimax approximation scalarSin = (((((-2.3889859e-08f * y2 + 2.7525562e-06f) * y2 - 0.00019840874f) * y2 + 0.0083333310f) * y2 - 0.16666667f) * y2 + 1.0f) * y; // 10-degree minimax approximation float p = ((((-2.6051615e-07f * y2 + 2.4760495e-05f) * y2 - 0.0013888378f) * y2 + 0.041666638f) * y2 - 0.5f) * y2 + 1.0f; scalarCos = sign * p; }
Unity中通过数学公式实现向量转四元数,Quaternion.LookRotation(dir)实现
于 2022-09-07 11:11:56 首次发布