最近研究了一下定位這個系統(tǒng),感覺還多有趣的,游戲社交(約*)。查了一下看到了這篇文章,其中講了一些方法,多不錯的。今天給大家介紹一種unity自帶的簡單的方法。
用什么?
LocationService
這是一個unity提供的地理位置的接口,我用的unity版本是5.4.3,不清楚是哪個版本中就有這個接口。簡單說一下這個東東吧。
三個屬性:
●isEnabledByUser:檢測是否有了GPS開啟。
●lastData:上一次更新位置信息的數(shù)據(jù),初始化都為0。LocationInfo類型。
●status:更新進程的狀態(tài)。狀態(tài)有Stopped、Initaializing、Running、Failed,這四個狀態(tài)。
兩個方法:
●Start:開始更新位置信息。
●Stop:停止更新位置信息。
LocationInfo
這是獲得地理位置的數(shù)據(jù)體。屬性有:
●altitude:海拔
●horizontalAccuracy:水平精度
●verticalAccuracy:垂直精度
●latitude:經(jīng)度
●longitude:緯度
●timestamp:時間節(jié)點
怎么用?
剛才講的LocationService是封裝在Input中的,這里使用了一個協(xié)成來獲得位置信息。
private IEnumerator GetLocationInfo()
{
//先判斷是否打開了定位
if (!Input.location.isEnabledByUser)
{
Debug.Log("沒有打開定位");
yield break;
}
//這里開起定位計算
Input.location.Start();
//時間為20秒
var maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing)
{
yield return new WaitForSeconds(1);
maxWait--;
}
if (maxWait < 1)
{
Debug.Log("時間到");
yield break;
}
if (Input.location.status == LocationServiceStatus.Failed)
{
Debug.Log("無法使用定位");
yield break;
}
Debug.Log("經(jīng)緯度: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " +
Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " +
Input.location.lastData.timestamp);
Input.location.Stop();
}
計算距離
計算距離這里有一個博客講的很好就不講了。哈哈哈。
這里我也做了一個小小的測試。這是測試代碼。這里個人覺得第二種會精確一些,并且代碼要少一些,看著舒服些。哈哈哈。