【问题标题】:Euler Rotation Issue欧拉旋转问题
【发布时间】:2019-05-19 00:25:48
【问题描述】:

我正在用 C# 编写一段简单的代码,以确保玩家模型的头部指向鼠标的 Vector3 位置 (lookPoint),但它夹在 90 度范围内,与躯干的任一侧成 45 度当前方向。

我已经尝试过欧拉角的结果,以确保我获得了所需的 y 轴旋转值,但我在欧拉角何时应该再次循环到 0 时遇到了困难,我不能似乎想知道如何解决它。

 minRot = myTorso.transform.rotation.eulerAngles.y-180f-45f;
 maxRot = myTorso.transform.rotation.eulerAngles.y-180f+45f;

 lookDirection = Mathf.Atan2(lookPoint.x - transform.position.x, lookPoint.z - transform.position.z);
 lookRotation = Mathf.Clamp(Mathf.Rad2Deg * lookDirection, minRot, maxRot);

 myHead.eulerAngles = new Vector3(0,lookRotation,0);

这会导致头部在无法确定它的最大值或最小值应该是什么时突然回到极端之一。

谁能帮我定义 minRot 和 maxRot 以便解释 180 度交叉?

【问题讨论】:

    标签: c# euler-angles


    【解决方案1】:

    这应该可以满足您的需求。我只是基于提供的变量和代码,所以事情可能无法完美运行。如果没有,请告诉我,我们可以调整:

    lookDirection = Mathf.Atan2(lookPoint.x - transform.position.x, 
                                lookPoint.z - transform.position.z) * Mathf.Rad2Deg;
    Quaternion q = Quaternion.Euler(new Vector3(0, lookDirection, 0));
    Quaternion targetRotation = new Quaternion();
    Quaternion torsoRotation = myTorso.transform.rotation;
    // Check if the angle is outside the 45degree range
    if (Quaternion.Angle(q, torsoRotation) <= 45.0f)
        targetRotation = q;
    else
    {
        // This is to check which direction we're out of range
        float d = Mathf.DeltaAngle(q.eulerAngles.y, torsoRotation.eulerAngles.y);
        if (d > 0.0f)
            target = torsoRotation * Quaternion.Euler(0, -45f, 0);
        else if (d < 0.0f)
            target = torsoRotation * Quaternion.Euler(0, 45f, 0);
    }
    myHead.rotation = targetRotation;
    

    【讨论】:

    • 谢谢!这完美!通过硬编码各种 if 语句来检查范围,我得到了一个“解决方案”,但这明显更加优雅和简洁。谢谢!
    • 没问题,很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2012-08-16
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    相关资源
    最近更新 更多