duck

Unity 3D Robot navmesh script step 2

Nov 14th, 2012
189
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 Robot : MonoBehaviour
  5. {
  6.    
  7.     Transform target;
  8.    
  9.     public float seeDistance = 20;
  10.     NavMeshAgent agent;
  11.     Animation avatar;
  12.     Transform eyes;
  13.    
  14.     // Use this for initialization
  15.     void Start ()
  16.     {
  17.         target = GameObject.FindGameObjectWithTag("Player").transform;
  18.         agent = GetComponent<NavMeshAgent> ();
  19.         avatar = GetComponentInChildren<Animation> ();
  20.         eyes = transform.Find ("Eyes");
  21.         StartCoroutine( Tracking() );
  22.     }
  23.    
  24.     IEnumerator Tracking ()
  25.     {
  26.         while (true) {
  27.             yield return new WaitForSeconds(1);
  28.            
  29.             Vector3 delta = target.position - eyes.position;
  30.            
  31.             Ray ray = new Ray (eyes.position, delta);
  32.             RaycastHit hit;
  33.            
  34.             if (Physics.Raycast (ray, out hit, seeDistance)) {
  35.                
  36.                 Debug.Log( hit.collider.name );
  37.                
  38.             }
  39.            
  40.         }
  41.        
  42.     }
  43.    
  44.    
  45.    
  46.     // Update is called once per frame
  47.     void Update ()
  48.     {
  49.        
  50.         agent.SetDestination (target.position);
  51.        
  52.         if (agent.velocity.magnitude > 0.1f) {
  53.             avatar.CrossFade ("run");
  54.         } else {
  55.             avatar.CrossFade ("idle");
  56.         }
  57.        
  58.        
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment