Advertisement
SvOzMaS

MoveToPoint

Dec 16th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MoveToPoint : MonoBehaviour {
  5.  
  6.     public GameObject target;
  7.     private NavMeshAgent navAgent;
  8.     public bool followTarget, followFromStart;
  9.     public bool randomTarget;
  10.     private bool isRandomTargetSet = false;
  11.     private bool isCalculatingPath = false;
  12.     private Vector2 randomPos;
  13.     public float randomPointRadius;
  14.  
  15.     // Use this for initialization
  16.     void Start() {
  17.         navAgent = gameObject.GetComponent<NavMeshAgent>();
  18.  
  19.         if (target && followFromStart) {
  20.             navAgent.SetDestination(target.transform.position);
  21.         }
  22.     }
  23.  
  24.     void Update() {
  25.         if (target && followTarget && !randomTarget) {
  26.             navAgent.SetDestination(target.transform.position);
  27.         }
  28.  
  29.  
  30.         if (randomTarget) {
  31.             if (!isRandomTargetSet && !isCalculatingPath) {
  32.                 StartCoroutine(setRandomTarget());
  33.                 isCalculatingPath = true;
  34.             }
  35.             else {
  36.                 if (Vector3.Distance(transform.position,  (Vector3)randomPos)<1) {
  37.                     isRandomTargetSet = false;
  38.                 }
  39.             }
  40.         }
  41.  
  42.     }
  43.  
  44.     private IEnumerator setRandomTarget() {
  45.  
  46.         Vector2 randomPos = Random.insideUnitCircle * randomPointRadius + new Vector2(transform.position.x, transform.position.z);
  47.  
  48.         navAgent.SetDestination(randomPos);
  49.  
  50.         //Wait until the path is calculated
  51.         while (navAgent.pathPending) {
  52.             yield return 0;
  53.         }
  54.  
  55.         //The newPos is not contained into the NavMesh, so try again
  56.         if (navAgent.pathStatus == NavMeshPathStatus.PathInvalid) {
  57.             StartCoroutine(setRandomTarget());
  58.         }
  59.         //The new position is valid
  60.         else {
  61.  
  62.             isRandomTargetSet = true;
  63.             isCalculatingPath = false;
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement