- Home /
Question by
DcoltGaming · Mar 16, 2020 at 12:00 AM ·
c#unity 5scripting problemvector3angle
How to make the calculated angle respective of the players rotation?
Hi,
I am using Vector3.Angle to calculate whether a object is to the left or to the right of my player so the object can work out which corridors to turn down.
The issue I have though, is that when the rotation of the player changes, it then throws out the logic of knowing what is left or right.
What I am struggling with is how do I make it so that the 0° position is relative to the rotation of my player?
I have attached a picture as an example.
angle-issue.jpg
(111.0 kB)
Comment
Answer by Namey5 · Mar 16, 2020 at 05:09 AM
If all you need to know is whether the object is on the left or right of the player, you can use the dot product;
//Assuming 'target' is the object's transform, this is the direction of the target from our transform
Vector3 dir = target.position - transform.position;
//Take the dot product with our transform's right vector
float side = Vector3.Dot (dir, transform.right);
if (side > 0f)
Debug.Log ("Object to the right.");
else if (side < 0f)
Debug.Log ("Object to the left".);
else
Debug.Log ("Object directly in front or behind.");