Tuesday, October 2, 2012

Basic Unity 3D Enemy follow Script

This script essentially allows the player to be followed by another "enemy" object. It's a .js you need to attach to your GameObject to instantiate.

  1. var closeEnoughDistance = 1; // stop moving once we get this close to the target
  2. var target : Transform; //the enemy's target
  3. var moveSpeed = 3; //move speed
  4. var rotationSpeed = 3; //speed of turning
  5. var attackThreshold = 1.5; // distance within which to attack
  6. var chaseThreshold = 10; // distance within which to start chasing
  7. var giveUpThreshold = 20; // distance beyond which AI gives up
  8. var attackRepeatTime = 1; // delay between attacks when within range
  9.  
  10. private var chasing = false;
  11. private var attackTime = Time.time;
  12.  
  13. var myTransform : Transform; //current transform data of this enemy
  14.  
  15. function Awake()
  16. {
  17.     myTransform = transform; //cache transform data for easy access/preformance 
  18.     }
  19.  
  20.  
  21. function Start()
  22. {
  23.      target = GameObject.FindWithTag("Player").transform; //target the player
  24.     }
  25.  
  26. function Update () 
  27. {
  28.     // check distance to target every frame:
  29.     var distance = (target.position - myTransform.position).magnitude;
  30.     
  31.     if (distance < closeEnoughDistance)
  32.     {
  33.     animation.Play("ZombieAttack");
  34.     }
  35.     
  36.     if (chasing) 
  37.     {
  38.         //rotate to look at the player
  39.         myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
  40.         Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
  41.  
  42.         // give up, if too far away from target:
  43.         if (distance > giveUpThreshold) 
  44.         {
  45.         chasing = false;
  46.         }
  47.         else if (distance > closeEnoughDistance)
  48.         {
  49.         myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
  50.         }
  51.         else if (distance < attackThreshold && Time.time > attackRepeatTime) 
  52.  
  53.         {
  54.         target.SendMessage("ApplyDamage",10);
  55.         }
  56.  
  57.         attackTime = Time.time+ attackRepeatTime;
  58.         }
  59.         else 
  60.         {
  61.         // not currently chasing.
  62.  
  63.         // start chasing if target comes close enough
  64.         if (distance < chaseThreshold) 
  65.         {
  66.         chasing = true;
  67. }
  68. }
  69. }

1 comment: