2014年8月25日 星期一

Unity 運用 LocationService Interface 實現定位功能

在Unity裡,也可利用現有的LocationService這個Interface來利用本身載具的定位功能,取得目前所在地的地理資訊(longitude,latitude),接下來也會寫一篇有關Unity實現Location Base Service的方法,所以這篇算是基本的前導。


以下實做的方法用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;
  }
 } 
}
大家也可以試試看!

2 則留言:

  1. 請問如何知道他(這隻程式)是否運作成功? print 的東西會顯示在哪?

    回覆刪除
  2. 張薄好猛ㄛ
    我是說張頭髮薄

    回覆刪除