以下實做的方法用C#撰寫,Code方面可讀性滿高的也很直覺,主要要注意使用StartCoroutine去等待GPS定位完成,而要提醒的是如果是在電腦上直接Play執行,或是Unity Remote是不會有結果的,建議各位包成APK檔直接在行動載具測試!
若要了解更加詳細,可參考 Unity 官方 LocationService 的 Scripting API。
using UnityEngine;
using System.Collections;
using System.Timers;
public class HSController : MonoBehaviour
{
LocationInfo currentGPSPosition;
public string gps_String;
void Start()
{
StartCoroutine (GetGps());
}
IEnumerator GetGps()
{
if (!Input.location.isEnabledByUser) //確認使用者是否有開啟載具的GPS服務
yield break;
Input.location.Start (); //開始抓取目前所在資訊,並設定maxWait最多等待20秒回覆
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait>0) {
yield return new WaitForSeconds(1);
maxWait--;
}//end while
if (maxWait < 1) {
print ("Time out");
yield break;
}
if (Input.location.status == LocationServiceStatus.Failed) {
print("Unable to determine device location");
yield break;
} else {
print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
currentGPSPosition = Input.location.lastData; //lastData就是儲存地理資訊的部分,可以像下一行如此的運用
gps_String = currentGPSPosition.longitude + "||" + currentGPSPosition.latitude;
print (gps_String);
Input.location.Stop();
yield break;
}
}
}
大家也可以試試看!
請問如何知道他(這隻程式)是否運作成功? print 的東西會顯示在哪?
回覆刪除張薄好猛ㄛ
回覆刪除我是說張頭髮薄