Files
GeoSusGame/Assets/Scripts/GPSManager.cs
2025-11-30 08:46:19 +01:00

69 lines
1.9 KiB
C#

using System.Collections;
using UnityEngine;
public class GPSManager : MonoBehaviour
{
[Header("GPS settings")]
public float Accuracy = 10f;
public float UpdateDistance = 5f;
public int MaxWait = 20;
[Header("GPS coordinates")]
private double[] LastCoords = new double[2];
private double[] FailsafeCoords = new double[] { 50.7727878, 15.0718625 };
private double? LastTime;
void Start()
{
StartCoroutine(UpdateGPS());
}
public double[] GetLastCoords()
{
if (LastCoords[0] == 0 && LastCoords[1] == 0) { return FailsafeCoords; }
return LastCoords;
}
IEnumerator UpdateGPS()
{
if (!Input.location.isEnabledByUser)
{
Debug.Log("GPS not enabled by user");
LastCoords = FailsafeCoords;
LastTime = null;
yield break;
}
Input.location.Start(Accuracy, UpdateDistance);
while (Input.location.status == LocationServiceStatus.Initializing && MaxWait > 0)
{
yield return new WaitForSeconds(1);
MaxWait--;
}
if (MaxWait < 1)
{
Debug.Log("GPS timed out");
LastCoords = FailsafeCoords;
LastTime = null;
yield break;
}
if (Input.location.status == LocationServiceStatus.Failed)
{
Debug.Log("GPS failed to determine device location");
LastCoords = FailsafeCoords;
LastTime = null;
yield break;
}
else
{
LastCoords[0] = Input.location.lastData.latitude;
LastCoords[1] = Input.location.lastData.longitude;
LastTime = Input.location.lastData.timestamp;
Debug.Log("GPS location: " + LastCoords[0] + ", " + LastCoords[1] + " (time: " + LastTime + ")");
}
yield return StartCoroutine(UpdateGPS());
}
}