Unity3D 经纬度与三维坐标相互转化

1.坐标分析

Unity3D 经纬度与三维坐标相互转化_第1张图片

假设经度角AOB用 Lng 表示,纬度角DOB用 Lat 表示,半径OD用 表示。

坐标点D为 (X,Y,Z),这里假设已知,实际也是很容易算得。

 

2.经纬度转空间坐标

转换公式:

Unity3D 经纬度与三维坐标相互转化_第2张图片

 

3.空间坐标转经纬度

转换公式:

Unity3D 经纬度与三维坐标相互转化_第3张图片

 

首先,实际上这里 Lng 和 Lat 是有正负的,这个可以用来区分南纬北纬,和东经西经。

4.Unity3D程序

(由于之前太忙,隔了好久终于来补了)

这里代码我放一个demo(如下图,这里假设白球为地球,红色小球为绕着转的物体)。代码中东西经度和南北纬度的判断,可能需要根据自己实际需要来调整,这里坐标最好统一化,让地球为原点;

对于经度匹配,可以旋转地球,使得地球的实际经度位置与求得的经度相同即可。

Unity3D 经纬度与三维坐标相互转化_第4张图片

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class coordinate : MonoBehaviour {

    public GameObject Earth; //地球
    public GameObject Sphere1; //绕地物体
    float myRadius;//距离

    float myLatitude; //纬度
    int   myLatDegree;//度
    float myLatMinute;//分
    float myLatSecond;//秒
    char  LatDire;

    float myLonitude; //经度
    int   myLonDegree;//度
    float myLonMinute;//分
    float myLonSecond;//秒
    char  LonDire;

	void Update () {
        GetComponent().text = myCalculate(Earth,Sphere1);
        //Debug.Log(myCalculate());
    }

    string myCalculate(GameObject myEarth, GameObject mySphere){
        myRadius = Vector3.Distance(myEarth.transform.position, mySphere.transform.position);

        myLatitude = Mathf.Asin(mySphere.transform.position.y / myRadius) * Mathf.Rad2Deg;//求纬度,并转成弧度
        //注:这里我是以 x,z 为水平面 ,即 y = 0 的轨道为赤道,在Unity中可以很直观地看出
        myLatDegree = (int)Mathf.Abs(myLatitude);//纬度均为正数,取绝对值,然后判断南北纬
        myLatMinute = (int)(Mathf.Abs(myLatitude) * 60) % 60;
        myLatSecond = (Mathf.Abs(myLatitude) * 3600) % 60;
        LatDire = myLatitude < 0 ? 'S' : 'N';

        myLonitude = Mathf.Atan2(mySphere.transform.position.z, mySphere.transform.position.x) * Mathf.Rad2Deg;//求经度
        myLonDegree = (int)Mathf.Abs(myLonitude);
        myLonMinute = (int)(Mathf.Abs(myLonitude) * 60) % 60;
        myLonSecond = (Mathf.Abs(myLonitude) * 3600) % 60;
        LonDire = myLonitude < 0 ? 'W' : 'E';

        return string.Format("{0}°{1}'{2:F0}\"{3}  {4}°{5}'{6:F0}\"{7}" , myLatDegree, myLatMinute, myLatSecond,LatDire,
            myLonDegree, myLonMinute, myLonSecond,LonDire);
        //关于string.Format用法可见这篇博客 https://blog.csdn.net/weixin_42513339/article/details/83057648
    }
}

 

你可能感兴趣的:(Unity3D)