Hey I am working with unity c#. I want to calculate the angle between two directions:…
- User
Hey I am working with unity c#. I want to calculate the angle between two directions: var v = owner.dir.Value.ToVector2(); var dir = new Vector3(v.x, 0, v.y); var destinationRot = Quaternion.LookRotation(dir); float angle = Quaternion.Dot(transform.rotation, destinationRot); Debug.Log("angle = " + angle);
- Assistant
In Unity, calculating the angle between two directions can be done using the
Vector3.Anglemethod. Your current approach using the dot product of quaternions isn't the right way to get the angle between two directions, and it doesn't give an angle in degrees.Here's a more straightforward and correct way to calculate and log the angle between two directions:
- Convert both directions to
Vector3. - Use
Vector3.Angleto compute the angle between the two directions in degrees.
csharp// Convert your directions to Vector3 as needed var v = owner.dir.Value.ToVector2(); var dir = new Vector3(v.x, 0, v.y); // Assuming you want the angle between the direction `dir` and the forward direction of your transform Vector3 forward = transform.forward; // Compute the angle between the two directions float angle = Vector3.Angle(forward, dir); // Log the angle Debug.Log("Angle between forward and dir: " + angle); - Convert both directions to
- User
angle is always positve how can I find out the + or -
- Assistant
You are correct that the
Vector3.Anglemethod only returns positive values. To determine whether the angle is positive or negative, you need to take the orientation into account. One common approach is to project the angle onto a plane and then use the cross product to determine the sign.Here's how you can do it:
- Calculate the unsigned angle using
Vector3.Angle. - Use the cross product to determine whether the calculated angle is clockwise or counterclockwise.
Here's an example:
csharp - Calculate the unsigned angle using