Advertisement
Guest User

AI

a guest
Nov 9th, 2017
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.34 KB | None | 0 0
  1. void ControlRandomWander()
  2.         {
  3.             float pointDist = Vector3.Distance(currentWanderPos, transform.position);
  4.  
  5.             if(pointDist < 2f || currentWanderPos == Vector3.zero)
  6.             {
  7.                 wanderWaitTimer += Time.deltaTime * 15;
  8.  
  9.                 anims.LookAround(true);
  10.  
  11.                 if (wanderWaitTimer >= wanderWaitTime)
  12.                 {
  13.                     Vector3 randPos = GetRandomPositionAroundTarget(transform.position, -wanderRadius, wanderRadius);
  14.  
  15.                     NavMeshPath pth = new NavMeshPath();
  16.                     NavMesh.CalculatePath(transform.position, randPos, agent.areaMask, pth);
  17.                     float pathDist = 0f;
  18.  
  19.                     if (pth.status == NavMeshPathStatus.PathComplete)
  20.                     {
  21.                         for (int i = 0; i < pth.corners.Length - 1; i++)
  22.                         {
  23.                             pathDist += Vector3.Distance(pth.corners[i], pth.corners[i + 1]);
  24.                         }
  25.  
  26.                         Debug.Log(pathDist);
  27.  
  28.                         if (pathDist <= wanderRadius)
  29.                         {
  30.                             currentWanderPos = randPos;
  31.  
  32.                             wanderWaitTime = Random.Range(wanderWaitMin, wanderWaitMax);
  33.  
  34.                             anims.LookAround(false);
  35.                             wanderWaitTimer = 0;
  36.  
  37.                             MoveToPosition(randPos, true);
  38.                         }
  39.                     }
  40.                 }
  41.             }
  42.             else
  43.             {
  44.                 if (agent.destination != currentWanderPos)
  45.                 {
  46.                     MoveToPosition(currentWanderPos, true);
  47.                 }
  48.             }
  49.         }
  50.  
  51. Vector3 GetRandomPositionAroundTarget(Vector3 pos, float minRange, float maxRange)
  52.         {
  53.             float offsetX = Random.Range(minRange, maxRange);
  54.             float offsetZ = Random.Range(minRange, maxRange);
  55.  
  56.             Vector3 orgPos = pos;
  57.  
  58.             orgPos.x += offsetX;
  59.             orgPos.z += offsetZ;
  60.  
  61.             NavMeshHit hit;
  62.             if(NavMesh.SamplePosition(orgPos, out hit, 5f, agent.areaMask))
  63.             {
  64.                 Debug.Log(hit.position);
  65.                 return hit.position;
  66.             }
  67.  
  68.             Debug.Log(hit.position);
  69.  
  70.             return pos;
  71.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement