MoveAlongPath.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Serialization;
  4. // ReSharper disable UnusedMember.Global
  5. namespace ARLocation
  6. {
  7. using Utils;
  8. /// <summary>
  9. /// This component, when attached to a GameObject, makes it traverse a
  10. /// path that interpolates a given set of geographical locations.
  11. /// </summary>
  12. [AddComponentMenu("AR+GPS/Move Along Path")]
  13. [HelpURL("https://http://docs.unity-ar-gps-location.com/guide/#movealongpath")]
  14. [DisallowMultipleComponent]
  15. public class MoveAlongPath : MonoBehaviour
  16. {
  17. [Serializable]
  18. public class PathSettingsData
  19. {
  20. /// <summary>
  21. /// The LocationPath describing the path to be traversed.
  22. /// </summary>
  23. [Tooltip("The LocationPath describing the path to be traversed.")]
  24. public LocationPath LocationPath;
  25. /// <summary>
  26. /// The number of points-per-segment used to calculate the spline.
  27. /// </summary>
  28. [Tooltip("The number of points-per-segment used to calculate the spline.")]
  29. public int SplineSampleCount = 250;
  30. /// <summary>
  31. /// If present, renders the spline in the scene using the given line renderer.
  32. /// </summary>
  33. [FormerlySerializedAs("lineRenderer")] [Tooltip("If present, renders the spline in the scene using the given line renderer.")]
  34. public LineRenderer LineRenderer;
  35. }
  36. [Serializable]
  37. public class PlaybackSettingsData
  38. {
  39. /// <summary>
  40. /// The speed along the path.
  41. /// </summary>
  42. [Tooltip("The speed along the path.")]
  43. public float Speed = 1.0f;
  44. /// <summary>
  45. /// The up direction to be used for orientation along the path.
  46. /// </summary>
  47. [Tooltip("The up direction to be used for orientation along the path.")]
  48. public Vector3 Up = Vector3.up;
  49. /// <summary>
  50. /// If true, play the path traversal in a loop.
  51. /// </summary>
  52. [Tooltip("If true, play the path traversal in a loop.")]
  53. public bool Loop = true;
  54. /// <summary>
  55. /// If true, start playing automatically.
  56. /// </summary>
  57. [Tooltip("If true, start playing automatically.")]
  58. public bool AutoPlay = true;
  59. [FormerlySerializedAs("offset")] [Tooltip("The parameters offset; marks the initial position of the object along the curve.")]
  60. public float Offset;
  61. }
  62. [Serializable]
  63. public class PlacementSettingsData
  64. {
  65. [Tooltip("The altitude mode. The altitude modes of the individual path locations are ignored, and this will be used instead.")]
  66. public AltitudeMode AltitudeMode = AltitudeMode.DeviceRelative;
  67. [Tooltip(
  68. "The maximum number of times this object will be affected by GPS location updates. Zero means no limits are imposed.")]
  69. public uint MaxNumberOfLocationUpdates = 4;
  70. }
  71. [Serializable]
  72. public class StateData
  73. {
  74. public uint UpdateCount;
  75. public Vector3[] Points;
  76. public int PointCount;
  77. public bool Playing;
  78. public Spline Spline;
  79. public Vector3 Translation;
  80. public float Speed;
  81. }
  82. public PathSettingsData PathSettings = new PathSettingsData();
  83. public PlaybackSettingsData PlaybackSettings = new PlaybackSettingsData();
  84. public PlacementSettingsData PlacementSettings = new PlacementSettingsData();
  85. public float Speed
  86. {
  87. get => state.Speed;
  88. set => state.Speed = value;
  89. }
  90. [Space(4.0f)]
  91. [Header("Debug")]
  92. [Tooltip("When debug mode is enabled, this component will print relevant messages to the console. Filter by 'MoveAlongPath' in the log output to see the messages.")]
  93. public bool DebugMode;
  94. [Space(4.0f)]
  95. private StateData state = new StateData();
  96. private ARLocationProvider locationProvider;
  97. private float u;
  98. private GameObject arLocationRoot;
  99. private Transform mainCameraTransform;
  100. private bool useLineRenderer;
  101. private bool hasInitialized;
  102. private GroundHeight groundHeight;
  103. private bool HeightRelativeToDevice => PlacementSettings.AltitudeMode == AltitudeMode.DeviceRelative;
  104. private bool HeightGroundRelative => PlacementSettings.AltitudeMode == AltitudeMode.GroundRelative;
  105. /// <summary>
  106. /// Change the `LocationPath` the GameObject will traverse. This will
  107. /// have the effect of reseting the movement to the start of the path.
  108. /// </summary>
  109. /// <param name="path"></param>
  110. public void SetLocationPath(LocationPath path)
  111. {
  112. PathSettings.LocationPath = path;
  113. state.PointCount = PathSettings.LocationPath.Locations.Length;
  114. state.Points = new Vector3[state.PointCount];
  115. u = 0;
  116. BuildSpline(locationProvider.CurrentLocation.ToLocation());
  117. }
  118. void Start()
  119. {
  120. if (PathSettings.LocationPath == null)
  121. {
  122. throw new NullReferenceException("[AR+GPS][MoveAlongPath]: Null Path! Please set the 'LocationPath' property!");
  123. }
  124. locationProvider = ARLocationProvider.Instance;
  125. mainCameraTransform = ARLocationManager.Instance.MainCamera.transform;
  126. arLocationRoot = ARLocationManager.Instance.gameObject; // Misc.FindAndLogError("ARLocationRoot", "[ARLocationMoveAlongPath]: ARLocationRoot GameObject not found.");
  127. Initialize();
  128. hasInitialized = true;
  129. }
  130. private void Initialize()
  131. {
  132. state.PointCount = PathSettings.LocationPath.Locations.Length;
  133. state.Points = new Vector3[state.PointCount];
  134. state.Speed = PlaybackSettings.Speed;
  135. Debug.Log(state.PointCount);
  136. Debug.Log(state.Points);
  137. useLineRenderer = PathSettings.LineRenderer != null;
  138. transform.SetParent(arLocationRoot.transform);
  139. state.Playing = PlaybackSettings.AutoPlay;
  140. u += PlaybackSettings.Offset;
  141. groundHeight = GetComponent<GroundHeight>();
  142. if (PlacementSettings.AltitudeMode == AltitudeMode.GroundRelative)
  143. {
  144. if (!groundHeight)
  145. {
  146. groundHeight = gameObject.AddComponent<GroundHeight>();
  147. groundHeight.Settings.DisableUpdate = true;
  148. }
  149. }
  150. else
  151. {
  152. if (groundHeight)
  153. {
  154. Destroy(groundHeight);
  155. groundHeight = null;
  156. }
  157. }
  158. if (!hasInitialized)
  159. {
  160. locationProvider.OnProviderRestartEvent(ProviderRestarted);
  161. }
  162. locationProvider.OnLocationUpdatedEvent(LocationUpdated);
  163. //if (locationProvider.IsEnabled)
  164. // {
  165. // LocationUpdated(locationProvider.CurrentLocation, locationProvider.LastLocation);
  166. //}
  167. }
  168. private void ProviderRestarted()
  169. {
  170. state.UpdateCount = 0;
  171. }
  172. public void Restart()
  173. {
  174. state = new StateData();
  175. Initialize();
  176. }
  177. /// <summary>
  178. /// Starts playing or resumes the playback.
  179. /// </summary>
  180. public void Play()
  181. {
  182. state.Playing = true;
  183. }
  184. /// <summary>
  185. /// Moves the object to the spline point corresponding
  186. /// to the given parameter.
  187. /// </summary>
  188. /// <param name="t">Between 0 and 1</param>
  189. public void GoTo(float t)
  190. {
  191. u = Mathf.Clamp(t, 0, 1);
  192. }
  193. /// <summary>
  194. /// Pauses the movement along the path.
  195. /// </summary>
  196. public void Pause()
  197. {
  198. state.Playing = false;
  199. }
  200. /// <summary>
  201. /// Stops the movement along the path.
  202. /// </summary>
  203. public void Stop()
  204. {
  205. state.Playing = false;
  206. u = 0;
  207. }
  208. private void BuildSpline(Location location)
  209. {
  210. for (var i = 0; i < state.PointCount; i++)
  211. {
  212. var loc = PathSettings.LocationPath.Locations[i];
  213. state.Points[i] = Location.GetGameObjectPositionForLocation(arLocationRoot.transform,
  214. mainCameraTransform, location, loc, HeightRelativeToDevice || HeightGroundRelative);
  215. Logger.LogFromMethod("MoveAlongPath", "BuildSpline", $"({gameObject.name}): Points[{i}] = {state.Points[i]}, geo-location = {loc}", DebugMode);
  216. }
  217. state.Spline = Misc.BuildSpline(PathSettings.LocationPath.SplineType, state.Points, PathSettings.SplineSampleCount, PathSettings.LocationPath.Alpha);
  218. }
  219. private void LocationUpdated(LocationReading location, LocationReading _)
  220. {
  221. Logger.LogFromMethod("MoveAlongPath", "LocationUpdated", $"({gameObject.name}): New device location {location}", DebugMode);
  222. if (PlacementSettings.MaxNumberOfLocationUpdates > 0 && state.UpdateCount > PlacementSettings.MaxNumberOfLocationUpdates)
  223. {
  224. Logger.LogFromMethod("MoveAlongPath", "LocationUpdated", $"({gameObject.name}): Max number of updates reached! returning", DebugMode);
  225. return;
  226. }
  227. BuildSpline(location.ToLocation());
  228. state.Translation = new Vector3(0, 0, 0);
  229. state.UpdateCount++;
  230. }
  231. private void Update()
  232. {
  233. if (!state.Playing)
  234. {
  235. return;
  236. }
  237. // If there is no location provider, or spline, do nothing
  238. if (state.Spline == null || !locationProvider.IsEnabled)
  239. {
  240. return;
  241. }
  242. // Get spline point at current parameter
  243. var s = state.Spline.Length * u;
  244. var data = state.Spline.GetPointAndTangentAtArcLength(s);
  245. var tan = arLocationRoot.transform.InverseTransformVector(data.tangent);
  246. transform.position = data.point;
  247. var groundY = 0.0f;
  248. if (groundHeight)
  249. {
  250. var position = transform.position;
  251. groundY = groundHeight.CurrentGroundY;
  252. position = MathUtils.SetY(position, position.y + groundY);
  253. transform.position = position;
  254. }
  255. // Set orientation
  256. transform.localRotation = Quaternion.LookRotation(tan, PlaybackSettings.Up);
  257. // Check if we reached the end of the spline
  258. u = u + (state.Speed * Time.deltaTime) / state.Spline.Length;
  259. if (u >= 1 && !PlaybackSettings.Loop)
  260. {
  261. u = 0;
  262. state.Playing = false;
  263. }
  264. else
  265. {
  266. u = u % 1.0f;
  267. }
  268. // If there is a line renderer, render the path
  269. if (useLineRenderer)
  270. {
  271. PathSettings.LineRenderer.useWorldSpace = true;
  272. var t = arLocationRoot.transform;
  273. state.Spline.DrawCurveWithLineRenderer(PathSettings.LineRenderer,
  274. p => MathUtils.SetY(p, p.y + groundY)); //t.TransformVector(p - state.Translation));
  275. }
  276. }
  277. private void OnDestroy()
  278. {
  279. locationProvider.OnLocationUpdatedDelegate -= LocationUpdated;
  280. locationProvider.OnRestartDelegate -= ProviderRestarted;
  281. }
  282. }
  283. }