- Home /
Problems with Vector3.angle and angle to target
I am having problems with Vector3.Angle and I have looked into this. The angle that is returning is wrong, it seems to be incorrectly using transform.forward. Here is my code:
float angleToTarg = Vector3.Angle(transform.forward, targetToAttack.transform.position);
Debug.Log("[shipDriver] AngleToTarget: " + angleToTarg);
The target is between 45 and 90 degrees to my right. I have another function that determine if my target is on the left or right and returns an integer.
In my test scene with only a reference object and the target, this code works perfectly. But in my game scene, it seems to not be using transform.forward correctly.
Positive z is indeed in front of both my target and my reference object in my normal scene (as well as my test scene). Here is an image of my scene i am having problems with (reference is on left, and target is on right):
Why would this happen? The angle that is return is 143, when it should be around 80.
If I use transform.right, the angle that is return is the same (which shouldnt be the case). If i use transform.forward*-1, the code seems to give a more reasonable answer of 42, but it still seems off.
Whats going on here?
PS: Yes, my objects are both position relatively the same in the y direction. They are only different in the x and z axis.
Answer by robertbu · Mar 04, 2013 at 04:37 AM
You are passing a position in world space as the second parameter. You need to pass it a vector starting at transform.position...something like:
float angleToTarg = Vector3.Angle(transform.forward, targetToAttack.transform.position - transform.position);