0

我有一个汽车游戏,只能沿 x 轴和 z 轴行驶。如果汽车开到正 z (rotation == 0),那么它必须做一些事情,如果它开到正 x (rotation == 90),那么它必须做其他事情,依此类推。

    if (transform.rotation.eulerAngles.y == 0)
    {
        richtung = 0;
        Debug.Log("north");
    }

    if (transform.rotation.eulerAngles.y == 90)
    {
        richtung = 1;
        Debug.Log("east");
    }

    if (transform.rotation.eulerAngles.y == -180 || transform.rotation.y == 180)
    {
        richtung = 2;
        Debug.Log("south");
    }

    if (transform.rotation.eulerAngles.y == -90)
    {
        richtung = 3;
        Debug.Log("west");
    }

它适用于北方和东方,但南方和西方不适用。即使我用旋转的汽车启动程序 == -180 || 180.我做错了什么?谢谢!

4

2 回答 2

2

您需要使用非负值,如文档所述,它必须在 0 到 360 之间。

if (transform.rotation.eulerAngles.y == 180)
{
    richtung = 2;
    Debug.Log("south");
}

if (transform.rotation.eulerAngles.y == 270)
{
    richtung = 3;
    Debug.Log("west");
}

您的第三种情况几乎是正确的,但不幸的是您使用transform.rotation.y而不是transform.rotation.eulerAngles.y.

正如@Everts 指出的那样,将这些值与“epsilon”值进行比较会更好,因为float并且double不是完全精确(因为它们存储在内存中的格式)。

Math.Abs(transform.rotation.eulerAngles.y - 180) < 0.001
于 2018-10-01T09:09:01.393 回答
2

由于您只是在四个方向上设置车辆,因此您可以同时设置更多。

假设您使用 A 和 D 键旋转车辆,车辆以richtung = 0 开始。

public enum Direction { North, East, South, West }
public Direction VehicleDirection{ get{ return (Direction)richtung; } } 
private int richtung = 0;
void Update()
{
    if(Input.GetKeyDown(KeyCode.A))
    {
        if(++richtung == 4){ richtung == 0; }
    }
    else if(Input.GetKeyDown(KeyCode.D))
    {
       if(--richtung < 0){ richtung == 3; }
    }
}

现在您不需要关心旋转,因为您现在可以使用richtung 的值。在其他任何地方,您都可以使用 VehicleDirection 更明确地指示它的前进方向。

于 2018-10-01T11:15:22.387 回答