首页 > 学院 > 开发设计 > 正文

Unity3D GPS获取玩家地理位置

2019-11-09 18:08:07
字体:
来源:转载
供稿:网友

using UnityEngine; using System.Collections;

public enum LocationError { ERROR_NONE, //没有错误 ERROR_NOT_ENABLED, //GPS未启用 ERROR_TIMEOUT, //请求超时 ERROR_FAILED, //请求失败

} public class LocationInfo { /// /// Geographical device location latitude. 纬度 /// public float latitude; /// /// Geographical device location longitude 经度 /// public float longitude; /// /// Geographical device location altitude /// public float altitude; /// /// Horizontal accuracy of the location. /// public float horizontalAccuracy; /// /// Vertical accuracy of the location. /// public float verticalAccuracy; /// /// Timestamp (in seconds since 1970) when location was last time updated /// public double timestamp;

public string error = null;public LocationError errcode = LocationError.ERROR_NONE;

}

public class LocationHelp : MonoBehaviour {

public static LocationHelp _instance=null;public static LocationHelp Instance{ get { return _instance; }}void Awake(){ _instance = this;}public delegate void GetLocationCallback(LocationInfo location);public static GetLocationCallback GetUserLocation;public void GetLocation(GetLocationCallback callback){ StartCoroutine(GetGPS(callback));}IEnumerator GetGPS(GetLocationCallback callback){ LocationInfo info = new LocationInfo(); if (!Input.location.isEnabledByUser) { info.errcode = LocationError.ERROR_NOT_ENABLED; info.error = "用户未开启GPS"; Debug.Log("用户未开启GPS"); callback(info); yield break; } // Input.location.Start(); Input.location.Start(5.0f, 5.0f); int maxWait = 5; while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) { yield return new WaitForSeconds(1); maxWait--; } if (maxWait < 1) { info.errcode = LocationError.ERROR_TIMEOUT; info.error = "获取GPS信息超时"; Debug.Log("获取GPS信息超时"); callback(info); yield break; } if(Input.location.status == LocationServiceStatus.Failed) { info.errcode = LocationError.ERROR_FAILED; info.error = "获取GPS信息失败"; Debug.Log("获取GPS信息失败"); callback(info); yield break; } info.latitude = Input.location.lastData.latitude; info.longitude = Input.location.lastData.longitude; info.altitude = Input.location.lastData.altitude; info.horizontalAccuracy = Input.location.lastData.horizontalAccuracy; info.verticalAccuracy = Input.location.lastData.verticalAccuracy; info.timestamp = Input.location.lastData.timestamp; callback(info);}

}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表