Reputation: 1
i am coding a 2D car racing game in Unity. Right now i want to check if the car is drifting with the Vector3.Dot function but the if state always return a value unequal one so it always prints the drifttrack. This happens even if the car stands still or the car is driving ahead.
//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);
}
Upvotes: 0
Views: 949
Reputation: 1
Thank you all for your answers.
Unfortunately it does not work.
First I normalized the Vectors:
Vector3 velo = myrigidbody2d.velocity;
velo.Normalize();
Vector3 direc = transform.TransformDirction(Vector3.forward);
direc.Normalize();
Then I compare both and check if they are unequal:
float dot = Vector3.Dot(velo, direc);
if (!Mathf.Approximately(dot, 1f))
{
Instantiate(drifttrack, tireLeft.transform.position,
tireLeft.transform.rotation);
Instantiate(drifttrack, tireRight.transform.position,
tireRight.transform.rotation);
}
It still instantiate my drifttrack without doing anything.
Upvotes: 0
Reputation: 10701
Float are not precise, you will most likely never get 1 but something like 1.00000000001 which is not 1 for a computer.
You need to use a range or approximate:
float dot = Vector3.Dot(myrigidbody2d.velocity, transform.TransformDirection(Vector3.forward));
if(Mathf.Approximately(dot, 1f)) { }
https://docs.unity3d.com/2018.2/Documentation/ScriptReference/Mathf.Approximately.html
Upvotes: 5