Get azimuth from relative direction

Wokay, I may have missed something basic (I do that a lot) but I really can’t think of a better way to do this.

Generally, I need to get an azimuth reading relative to a transform.

Here’s what I’ve done so far.

var direction = transform.InverseTransformDirectiontransform.position-target.position).normalized);
var quadrant = transform.InverseTransformPoint(target.position);
//or
var quadrant = Vector3.Dot(transform.forward,direction);
//Compare quadrant and direction to get approximate direction

It works well for approximate directions but I want to get a nice precise reading like in a compass, albeit with a relative zero. And it’s clunky as hell.

Thanks in advance!

If you want an accurate azimuth then you can use arctan on the z and x components. Try

float angle=Mathf.Atan2(relDir.z, relDir.x)

Or you could have an empty gameObject, well I don’t know much about your game but say you instantiate an empty gameObject at your players location (assuming you have a player) anyway at the location you want to find the angle from.

Then have that game object lookat the star and the the azimuth should be 360 - gameObject.transform.eulerAngles.x e.g. I reference the empty game object as emptyPlayer and the the star as star:

Debug.Log (emptyPlayer.transform.eulerAngles);
emptyPlayer.transform.LookAt(star.transform.position);
Debug.Log (360f - emptyPlayer.transform.rotation.eulerAngles.x);

That’s in C# but should be pretty similar in JS.