Finding the angle between a direction and a point

I wish to find the angle (theta) between an objects transform.forward vector and an arbitrary target point.

Ive tried doing a Vector3.Angle on the transform.forward vector and subtracting that from the Vector3.Angle of the target postiion - the transform position but the numbers seem all skewed.

I’m using it in a 2d environment.

Im sure there is a really easy way… I’m just missing it…

Here the math that should get you started

wouldn’t this only be correct if the target point is, in this case on the zero x axis, making the triangle a right angle? I need to do something similar and my trig maths was a long time ago.

Matt.

If you rotate the right triangle (making it non zero x), it still would be a right triangle. The extra calculations involved are to find the perpendicular distance between the top of the triangle and its foot. For this, dot product is your friend.

thanks for the replies, I am down with the trig solution, I was just wondering if there was a smart in built function that I missed.

I’ll google the dot product as well or would projecting the transform onto the target vector suffice…

Thanks again

Vector3.Angle should do what you want and Vector3.Cross should give you the axis to rotate around of.

Vector3 targetDir =m_waypoint.transform.position - transform.position;
		targetDir = targetDir.normalized;
		
		float dot = Vector3.Dot(targetDir, transform.forward);
		float angle = Mathf.Acos( dot ) * Mathf.Rad2Deg;

This is what seems to work well for me,
the angle is always positive, so I also use a cross product

Vector3 normalizedDirection = m_waypoint.transform.position-transform.position;
		
		float whichWay=Vector3.Cross(transform.forward, normalizedDirection).y; //Return left or right?

To determine if its CW or CCW (ones positive, ones negative above)…

But after your post rozgo I have indeed found that the Vector.Angle is returning the same result… and I can use the cross product result to determine direction.

Cheers!

4 Likes

@blastone Thanks for the Vector.Cross, I was looking for some code to determine if a vector is positve or negative. Vector3.Cross did the trick. Thanks!

Thank you! I am searching for this solution too! I am try to implement this to my ai so that it can decide steer left or right, Vector.Cross helps!

You can actually use Vector3.SignedAngle to get the angle and direction. Check it out here

1 Like