title: Making a Compass point to a particular location in Unity
body: <p>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.  </p>
  
  <p>I'm using the curved geometry bearing equation from here: <a href="http://www.yourhomenow.com/house/haversine.html" rel="nofollow">http://www.yourhomenow.com/house/haversine.html</a></p>
  
  <ol>
  <li>Get current location. </li>
  <li>Calculate bearing from current location to target location. </li>
  <li><p>Rotate screen compass relative to true north. </p>
  
  <pre><code>// 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));
  </code></pre></li>
  </ol>
  
  <p>If I remove the bearing offset in that code, it points north enough for a digital compass. </p>