使Compass指向Unity中的特定位置

时间:2014-04-21 23:02:06

标签: android unity3d digital-compass

我正在尝试制作一个指向Unity程序中自定义位置的指南针。然而,它完全关闭,它通常指向错误的方向,我似乎无法弄清楚我的逻辑有什么问题。

我正在使用弯曲几何轴承方程式:http://www.yourhomenow.com/house/haversine.html

  1. 获取当前位置。
  2. 计算从当前位置到目标位置的方位。
  3. 相对于真北向旋转屏幕指南针。

    // 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));
    
  4. 如果我删除了该代码中的轴承偏移量,它指向足够北的数字罗盘。

1 个答案:

答案 0 :(得分:1)

确保所有角度都是弧度而不是度数。

Mathf.Deg2Rad等情况下使用Mathf.Sin(dLon * Mathf.Deg2Rad)会产生正确的结果。 Haversine公式仅适用于弧度角度。