Unity Vector3.Dot错误的返回值

0 unity-game-engine

我在Unity编写2D赛车游戏.现在我想检查汽车是否漂移了Vector3.Dot函数,但if状态总是返回一个不相等的值,所以它总是打印漂移轨迹.即使汽车静止不动或汽车驶向前方,也会发生这种情况.

//Blickrichtung und Fahrtrichtung stimmen nicht überein
    //Driftspuren werden gezeichnet 
    if (1 != Vector3.Dot(myrigidbody2d.velocity, transform.TransformDirection(Vector3.forward)))
    { 
        Instantiate(drifttrack, tireLeft.transform.position, tireLeft.transform.rotation);
        Instantiate(drifttrack, tireRight.transform.position, tireRight.transform.rotation);
    }
Run Code Online (Sandbox Code Playgroud)

Eve*_*rts 5

浮点数不精确,你很可能永远不会得到1但是像1.00000000001这样的计算机不是1.

您需要使用范围或近似值:

float dot = Vector3.Dot(myrigidbody2d.velocity, transform.TransformDirection(Vector3.forward));
if(Mathf.Approximately(dot, 1f)) { }
Run Code Online (Sandbox Code Playgroud)

https://docs.unity3d.com/2018.2/Documentation/ScriptReference/Mathf.Approximately.html