基于相机旋转控制角色运动的简单数学

时间:2018-04-15 05:52:04

标签: c# unity3d math

我有一个名为myCamera的GameObject。我试图使用所述GameObject的欧拉角来确定角色应该朝什么方向移动。预期返回值的示例位于:

如果0度x = 1; z = 0
如果90度x = 0; z = 1
如果180度x = -1; z = 0;
如果270度x = 0; z = -1;

目前的代码如下:

    // TempVar[0] = tempX; [2] = finalX; [1] = finalZ;
    myCameraRotation = myCamera.transform.rotation.eulerAngles;
    if (myCameraRotation.y > 180f)
    {
        tempVar[0] = (int)myCameraRotation.y - 360f;
        Debug.Log("Over 180 - New Value: " + tempVar[0]);
    }
    else
    {
        tempVar[0] = (int)myCameraRotation.y;
        Debug.Log("Under 180 - Passing Value: " + tempVar[0]);
    }
    if (tempVar[0] > -90 && tempVar[0] <= 90)
    {
        tempVar[1] = (1 * Mathf.Abs(1 - (tempVar[0] / 90)));
    } // Calculate Z
    else if (tempVar[0] <= -90 && tempVar[0] > 90)
    {
        tempVar[1] = ((0 - 1) * Mathf.Abs(1 - (tempVar[0] / 90)));
    } // Calculate Z
    if (tempVar[0] > 0 && tempVar[0] <= 180)
    {
        tempVar[2] = (1 * Mathf.Abs(1 - (tempVar[0] / 90) / 2));
    } // Calculate X
    else if (tempVar[0] <= 0 && tempVar[0] > 180)
    {
        tempVar[2] = (-1 * Mathf.Abs(1 - (tempVar[0] / 90) / 2));
    } // Calculate X
    Debug.Log("Z Value : " + tempVar[1]);
    Debug.Log("X Value : " + tempVar[2]);

这是输出一些非常时髦的价值观,说实话,我不确定它是怎么回事。如前所述,我得到了myCamera GameObject的欧拉角,而不是旋转。

我越努力尝试这一点就越多可怕的数字开始出现,任何知道数学的人都会非常感激。

1 个答案:

答案 0 :(得分:2)

如果y旋转是对象的唯一旋转,则可以使用对象矩阵的第一列作为向前方向。

如果有更多变换,您可以计算出所需的方向:

x = Math.Cos(myCameraRotation.y);
z = Math.Sin(myCameraRotation.y);