A problem with calculating angles of objects.
In Unity 3D, How do I calculate the angles of the objects in the figure and find the object with the closest angle to the target?
Answer by Glenn-Korver · Oct 21, 2018 at 10:58 PM
Try reading up upon the "Dot Product" function/formula, which will allow you to calculate the angle between 2 normalized directions. Then do these for all objects you are interested in and selct the one with the smallest angle
Answer by UnityCoach · Oct 22, 2018 at 10:30 AM
As @Glenn-Korver suggested, you can use Vector3.Dot()
float dot_product = Vector3.Dot(transform.forward, (target.position - transform.position).normalized);
This will return a value of 1 when directions align perfectly, 0 when they're perpendicular. Or you can use Vector3.Angle()
float angle = Vector3.Angle (transform.forward, (target.position - transform.position).normalized);
This will return the angle in degrees.
This video shows this technique to highlight objects as you look at them in a VR project. This is from my Introduction to VR course, available here.
Your answer
Follow this Question
Related Questions
Rotating & fixing the position of an object to one spot 1 Answer
[Editor Extensions] - Rotate object in editor mode 0 Answers
Transform.LookAt rotate on x-axis 2 Answers
How to set limitations on rotateAround in C#? 1 Answer
Move a game object away from another game object based on the angle difference 1 Answer