Advertisement
duck

Unity 3D Navesh Agent Control - step 2

Feb 27th, 2013
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.27 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class AgentControl : MonoBehaviour {
  5.    
  6.     public Transform target;
  7.     NavMeshAgent agent;
  8.     float originalSpeed;
  9.    
  10.     // Use this for initialization
  11.     void Start () {
  12.         agent = GetComponent<NavMeshAgent>();
  13.         originalSpeed = agent.speed;
  14.        
  15.         StartCoroutine( LookForTarget() );
  16.        
  17.     }
  18.    
  19.     IEnumerator LookForTarget()
  20.     {
  21.        
  22.         while(true)
  23.         {
  24.            
  25.             Vector3 direction = (target.position+Vector3.up) - transform.position;
  26.             Ray ray = new Ray( transform.position, direction );
  27.             RaycastHit hit;
  28.            
  29.             Debug.DrawRay( ray.origin, ray.direction*direction.magnitude );
  30.            
  31.             if ( Physics.Raycast( ray, out hit ) )
  32.             {
  33.                 if (hit.collider.tag == "Player")
  34.                 {
  35.                     agent.SetDestination( target.position );
  36.                 }
  37.                
  38.                 Debug.Log (hit.collider.name);
  39.             }
  40.        
  41.            
  42.             yield return new WaitForSeconds(Random.value+0.5f);
  43.         }
  44.        
  45.        
  46.     }
  47.    
  48.    
  49.    
  50.     // Update is called once per frame
  51.     void Update () {
  52.        
  53.         int mask = 1 << NavMesh.GetNavMeshLayerFromName("No Running");
  54.        
  55.         NavMeshHit navHit;
  56.         agent.SamplePathPosition (-1, 0, out navHit);
  57.        
  58.        
  59.         if ( (navHit.mask & mask) != 0)
  60.         {
  61.             agent.speed = originalSpeed * 0.3f;
  62.            
  63.         } else {
  64.             agent.speed = originalSpeed;
  65.         }  
  66.        
  67.    
  68.     }
  69.    
  70.    
  71.    
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement