ClickedPointsMovement.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class ClickedPointsMovement : MonoBehaviour { public float speed = 15; Queue<Vector3> targetPointsQueue = new Queue<Vector3>(); RaycastHit hit; Camera mainCam; Coroutine _MoveCR; int layerMask; void Awake() { mainCam = Camera.main; layerMask = LayerMask.GetMask( "Ground" ); } void Update() { if (Input.GetMouseButtonDown(0)) { if (Physics.Raycast(mainCam.ScreenPointToRay(Input.mousePosition), out hit, 100, layerMask)) { targetPointsQueue.Enqueue(hit.point); if (_MoveCR == null ) { _MoveCR = StartCoroutine(MoveThroughPoints(targetPointsQueue)); } } } } IEnumerator MoveThroughPoints(Queue<Vector3> points) { while (points.Count > 0) { Vector3 targetPoint = points.Dequeue(); targetPoint = new Vector3(targetPoint.x, transform.position.y, targetPoint.z); while (Vector3.Distance(transform.position, targetPoint) > 0.01f) { transform.position = Vector3.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime); yield return null ; } } _MoveCR = null ; } } |