| | | 1 | | using System.Collections; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using UnityEngine; |
| | | 4 | | using UnityEngine.UI; |
| | | 5 | | |
| | | 6 | | namespace DroneGame |
| | | 7 | | { |
| | | 8 | | public class Drone : MonoBehaviour |
| | | 9 | | { |
| | | 10 | | Grid _grid; |
| | | 11 | | Button _button; |
| | | 12 | | |
| | | 13 | | public bool alreadyMoving; |
| | | 14 | | |
| | | 15 | | /// <summary>Set the move speed of the drone</summary> |
| | | 16 | | [SerializeField] |
| | | 17 | | [Range(0.1f, 10.0f)] |
| | | 18 | | float _moveSpeed; |
| | | 19 | | |
| | | 20 | | /// <summary>This is here to mostly just setup the height, but it's a vector3 to facilitate to use in math</summary> |
| | | 21 | | [SerializeField] Vector3 _coordinateAdjustment; |
| | | 22 | | |
| | | 23 | | /// <summary>Default Unity event, Start executes when th object is instantiated and happens after Awake is executed< |
| | | 24 | | public void Initialize(Grid grid) |
| | 0 | 25 | | { |
| | 0 | 26 | | _grid = grid; |
| | 0 | 27 | | _button = GameObject.Find("CalculateAndMoveButton").GetComponent<Button>() ?? throw new("Button not found"); |
| | 0 | 28 | | transform.position = _grid.GetTileWorldCoordinate("A1") + _coordinateAdjustment; |
| | 0 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary>This function is meant to be executed as a coroutine |
| | | 32 | | /// Make drone move along the specified path.</summary> |
| | | 33 | | public IEnumerator FollowPath(List<TileData> path) |
| | 1 | 34 | | { |
| | 1 | 35 | | if (alreadyMoving) throw new("Drone is already moving"); |
| | | 36 | | |
| | 1 | 37 | | alreadyMoving = true; |
| | | 38 | | #if !UNITY_INCLUDE_TESTS |
| | | 39 | | _button.interactable = false; |
| | | 40 | | #endif |
| | 4 | 41 | | for (int tileIndex = 1; tileIndex < path.Count; tileIndex++) |
| | 1 | 42 | | { |
| | 1 | 43 | | var currLerp = 0f; |
| | 1 | 44 | | var previousTile = path[tileIndex - 1].globalCoordinates + _coordinateAdjustment; |
| | 1 | 45 | | var nextTile = path[tileIndex].globalCoordinates + _coordinateAdjustment; |
| | | 46 | | |
| | 3 | 47 | | while (currLerp <= 1f) |
| | 2 | 48 | | { |
| | 2 | 49 | | var currSpeed = _moveSpeed * Time.deltaTime; |
| | 2 | 50 | | transform.position = Vector3.Lerp(previousTile, nextTile, currLerp); |
| | | 51 | | |
| | | 52 | | // And this is the reason why this works |
| | | 53 | | // Wait for the next frame to continue the code execution. |
| | 2 | 54 | | yield return null; |
| | 2 | 55 | | currLerp += currSpeed; |
| | 2 | 56 | | } |
| | 1 | 57 | | } |
| | 1 | 58 | | alreadyMoving = false; |
| | | 59 | | #if !UNITY_INCLUDE_TESTS |
| | | 60 | | _button.interactable = true; |
| | | 61 | | #endif |
| | 1 | 62 | | } |
| | | 63 | | } |
| | | 64 | | } |