I'm trying to make a compass that points to a custom location in a Unity program. However it's completely off, it points in generally the wrong direction and I can't quite seem to figure out what is wrong with my logic.
I'm using the curved geometry bearing equation from here: http://www.yourhomenow.com/house/haversine.html
- Get current location.
- Calculate bearing from current location to target location.
Rotate screen compass relative to true north.
// Calculate bearing between current location and target location // Get current GPS location float lat1 = Input.location.lastData.latitude; float lon1 = Input.location.lastData.longitude; float lat2 = TargetLatitude; float dLon = TargetLongitude - lon1; // Calculate bearing var y = Mathf.Sin(dLon) * Mathf.Cos(lat2); var x = Mathf.Cos(lat1) * Mathf.Sin(lat2) - Mathf.Sin(lat1) * Mathf.Cos(lat2) * Mathf.Cos(dLon); var brng = ((Mathf.Atan2(y, x)*(180.0f/Mathf.PI)) + 360.0f) % 360.0f; Dump.text = brng.ToString(); // Rotate the to target location relative to north. Z axis pointing out of screen. transform.eulerAngles = new Vector3(0, 0, Mathf.MoveTowardsAngle(transform.localEulerAngles.z, Input.compass.trueHeading + brng, COMPASS_MAXDELTA));
If I remove the bearing offset in that code, it points north enough for a digital compass.