Advertisement
Guest User

Untitled

a guest
Jul 27th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.69 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Unit : MonoBehaviour {
  5.  
  6.     public Transform target;
  7.     float speed = 20;
  8.     Vector2[] path;
  9.     int targetIndex;
  10.  
  11.     void Start()
  12.     {
  13.         PathrequestManager.RequestPath(transform.position, target.position, OnPathFound);
  14.     }
  15.  
  16.     public void OnPathFound(Vector2[] newPath, bool pathSuccessful)
  17.     {
  18.         if (pathSuccessful)
  19.         {
  20.             path = newPath;
  21.             targetIndex = 0;
  22.             StopCoroutine("FollowPath");
  23.             StartCoroutine("FollowPath");
  24.         }
  25.     }
  26.  
  27.     IEnumerator FollowPath()
  28.     {
  29.         Vector2 currentWaypoint = path[0];
  30.  
  31.         while (true)
  32.         {
  33.             if (transform.position == currentWaypoint)
  34.             {
  35.                 targetIndex++;
  36.                 if (targetIndex >= path.Length)
  37.                 {
  38.                     yield break;
  39.                 }
  40.                 currentWaypoint = path[targetIndex];
  41.             }
  42.  
  43.             transform.position = Vector2.MoveTowards(transform.position, currentWaypoint, speed * Time.deltaTime);
  44.             yield return null;
  45.  
  46.         }
  47.     }
  48.  
  49.     public void OnDrawGizmos()
  50.     {
  51.         if (path != null)
  52.         {
  53.             for (int i = targetIndex; i < path.Length; i++)
  54.             {
  55.                 Gizmos.color = Color.black;
  56.                 Gizmos.DrawCube(path[i], Vector3.one);
  57.  
  58.                 if (i == targetIndex)
  59.                 {
  60.                     Gizmos.DrawLine(transform.position, path[i]);
  61.                 }
  62.                 else
  63.                 {
  64.                     Gizmos.DrawLine(path[i - 1], path[i]);
  65.                 }
  66.             }
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement