duck

Unity 3D Navesh Agent Control - step 3

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