Unity中通过数学公式实现向量转四元数,Quaternion.LookRotation(dir)实现

 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;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值