I am using google API to show a map in unity and also generate object on map's location from player position. Now I want to know actual direction. It means identify direction (east-west) from google maps or google API.
I made a code but it doesn't give me actual direction.
var v = transform.forward;
v.y = 0;
v.Normalize();
if (Vector3.Angle(v, Vector3.forward) <= 45.0) {
Debug.Log("North");
}
else if (Vector3.Angle(v, Vector3.right) <= 45.0) {
Debug.Log("East");
}
else if (Vector3.Angle(v, Vector3.back) <= 45.0) {
Debug.Log("South");
}
else {
Debug.Log("West");
}
using
Vector3.forwardreturns you the forward Z axis direction of Unity itself. This depends entirely on the orientation of your device when you started Unity/your app and has nothing to do with real world coordinates.
You are probably rather looking for
Compasswhich returns the actual orientation of your phone e.g. usingmagneticHeadingor using the
trueHeadingSo for your use case you would simply use e.g.
In the little demo you can see the blue pointer for the object's forward direction and the red vector for the north direction. You can see how the
Headingenum value changes according to the objects orientation.Since I did it on a PC I had to manually "adjust" a north direction, later you will get this from your phone.