Search Unity

Free Simple AI Behavioral script

Discussion in 'Scripting' started by Ezzerland, May 16, 2011.

Thread Status:
Not open for further replies.
  1. Ezzerland

    Ezzerland

    Joined:
    Jul 1, 2010
    Posts:
    405
    I designed this for a project back in November. It's a simple AI script that allows for quite a good bit of customization on what the AI unit will do. I'd been thinking for a while now to post it, but, never really got around to it. Please keep in mind that I haven't touched the script since I wrote it and I also never fully tested/debugged it. So if there is anything not working, just post back/ask and when I have a moment I'll look.

    To get it to work, just attach it and a CharacterController to your enemy (or a box for a test) and look at the list of settings in the inspector. If you are unsure what anything means, it is all noted in detail in the script itself. Please keep in mind this is a Behavioral script, meaning this will not make your enemy attack, animate it, teach your dog tricks, or magically turn your game into the fully functional version of what's in your head. If you'd like the methods for those, please visit _____________ ____ _______ ____ and ____ to the ____ of _____. That should pretty much take care of anything you need.

    Enjoy.

    Code (csharp):
    1. /*
    2.         Copyright 2010 Black Storms Studios, LLC.
    3.         @Author - Rob Pearson
    4.         @Date - November 2010
    5.         @Contact - RIPearson@BlackStormsStudios.com
    6.         @Script -
    7.         @Connections - requires CharacterController attached to enemy.
    8.         @TODO -
    9. */
    10.  
    11. using UnityEngine;
    12. using System.Collections;
    13.  
    14. public class SimpleEnemyAIBehavior : MonoBehaviour {
    15.    
    16.     //Inspector initiated variables. Defaults are set for ease of use.
    17.     public bool on = true; //Is the AI active? this can be used to place pre-set enemies in you scene.
    18.     public bool canFly = false; //Flying alters float behavior to ignore gravity. The enemy will fly up or down only to sustain floatHeight level.
    19.     public float floatHeight = 0.0f; //If it can fly/hover, you need to let the AI know how high off the ground it should be.
    20.     public bool runAway = false; //Is it the goal of this AI to keep it's distance? If so, it needs to have runaway active.
    21.     public bool runTo = false; //Opposite to runaway, within a certain distance, the enemy will run toward the target.
    22.     public float runDistance = 25.0f; //If the enemy should keep its distance, or charge in, at what point should they begin to run?
    23.     public float runBufferDistance = 50.0f; //Smooth AI buffer. How far apart does AI/Target need to be before the run reason is ended.
    24.     public int walkSpeed = 10; //Standard movement speed.
    25.     public int runSpeed = 15; //Movement speed if it needs to run.
    26.     public int randomSpeed = 10; //Movement speed if the AI is moving in random directions.
    27.     public float rotationSpeed = 20.0f; //Rotation during movement modifier. If AI starts spinning at random, increase this value. (First check to make sure it's not due to visual radius limitations)
    28.     public float visualRadius = 100.0f; //How close does the player need to be to be seen by the enemy? Set to 0 to remove this limitation.
    29.     public float moveableRadius = 200.0f; //If the player is too far away, the AI will auto-matically shut down. Set to 0 to remove this limitation.
    30.     public float attackRange = 10.0f; //How close does the enemy need to be in order to attack?
    31.     public float attackTime = 0.50f; //How frequent or fast an enemy can attack (cool down time).
    32.     public bool useWaypoints = false; //If true, the AI will make use of the waypoints assigned to it until over-ridden by another functionality.
    33.     public bool reversePatrol = true; //if true, patrol units will walk forward and backward along their patrol.
    34.     public Transform[] waypoints; //define a set path for them to follow.
    35.     public bool pauseAtWaypoints = false; //if true, patrol units will pause momentarily at each waypoint as they reach them.
    36.     public float pauseMin = 1.0f; //If pauseAtWaypoints is true, the unit will pause momentarily for minmum of this time.
    37.     public float pauseMax = 3.0f; //If pauseAtWaypoints is true, the unit will pause momentarily formaximum of this time.
    38.     public float huntingTimer = 5.0f; //Search for player timer in seconds. Minimum of 0.1
    39.     public bool estimateElevation = false; //This implements a pause between raycasts for heights and guestimates the need to move up/down in height based on the previous raycast.
    40.     public float estRayTimer = 1.0f; //The amount of time in seconds between raycasts for gravity and elevation checks.
    41.     public bool requireTarget = true; //Waypoint ONLY functionality (still can fly and hover).
    42.     public Transform target; //The target, or whatever the AI is looking for.
    43.    
    44.    
    45.     //private script handled variables
    46.     private bool initialGo = false; //AI cannot function until it is initialized.
    47.     private bool go = true; //An on/off override variable
    48.     private Vector3 lastVisTargetPos; //Monitor target position if we lose sight of target. provides semi-intelligent AI.
    49.     CharacterController characterController; //CC used for enemy movement and etc.
    50.     private bool playerHasBeenSeen = false; //An enhancement to how the AI functions prior to visibly seeing the target. Brings AI to life when target is close, but not visible.
    51.     private bool enemyCanAttack = false; //Used to determine if the enemy is within range to attack, regardless of moving or not.
    52.     private bool enemyIsAttacking = false; //An attack interuption method.
    53.     private bool executeBufferState = false; //Smooth AI buffer for runAway AI. Also used as a speed control variable.
    54.     private bool walkInRandomDirection = false; //Speed control variable.
    55.     private float lastShotFired; //Used in conjuction with attackTime to monitor attack durations.
    56.     private float lostPlayerTimer; //Used for hunting down the player.
    57.     private bool targetIsOutOfSight; //Player tracking overload prevention. Makes sure we do not call the same coroutines over and over.
    58.     private Vector3 randomDirection; //Random movement behaviour setting.
    59.     private float randomDirectionTimer; //Random movement behaviour tracking.
    60.     private float gravity = 20.0f; //force of gravity pulling the enemy down.
    61.     private float antigravity = 2.0f; //force at which floating/flying enemies repel
    62.     private float estHeight = 0.0f; //floating/flying creatures using estimated elevation use this to estimate height necessities and gravity impacts.
    63.     private float estGravityTimer = 0.0f; //floating/flying creatures using estimated elevation will use this to actually monitor time values.
    64.     private int estCheckDirection = 0; //used to determine if AI is falling or not when estimating elevation.
    65.     private bool wpCountdown = false; //used to determine if we're moving forward or backward through the waypoints.
    66.     private bool monitorRunTo = false; //when AI is set to runTo, they will charge in, and then not charge again to after far enough away.
    67.     private int wpPatrol = 0; //determines what waypoint we are heading toward.
    68.     private bool pauseWpControl; //makes sure unit pauses appropriately.
    69.     private bool smoothAttackRangeBuffer = false; //for runAway AI to not be so messed up by their visual radius and attack range.
    70.    
    71.    
    72.  
    73.     //---Starting/Initializing functions---//
    74.     void Start() {
    75.         StartCoroutine(Initialize()); //co-routine is used incase you need to interupt initiialization until something else is done.
    76.     }
    77.    
    78.     IEnumerator Initialize() {
    79.         if ((estimateElevation)  (floatHeight > 0.0f)) {
    80.             estGravityTimer = Time.time;
    81.         }
    82.         characterController = gameObject.GetComponent<CharacterController>();
    83.         initialGo = true;
    84.         yield return null;
    85.     }
    86.    
    87.    
    88.    
    89.     //---Main Functionality---//
    90.     void Update () {
    91.         if (!on || !initialGo) {
    92.             return;
    93.         } else {
    94.             AIFunctionality();
    95.         }
    96.     }
    97.    
    98.     void AIFunctionality() {
    99.         if ((!target)  (requireTarget)) {
    100.             return; //if no target was set and we require one, AI will not function.
    101.         }
    102.        
    103.         //Functionality Updates
    104.         lastVisTargetPos = target.position; //Target tracking method for semi-intelligent AI
    105.         Vector3 moveToward = lastVisTargetPos - transform.position; //Used to face the AI in the direction of the target
    106.         Vector3 moveAway = transform.position - lastVisTargetPos; //Used to face the AI away from the target when running away
    107.         float distance = Vector3.Distance(transform.position, target.position);
    108.        
    109.         if (go) {
    110.             MonitorGravity();
    111.         }
    112.        
    113.         if (!requireTarget) {
    114.             //waypoint only functionality
    115.             Patrol();
    116.         } else if (TargetIsInSight ()) {
    117.             if (!go) { //useWaypoints is false and the player has exceeded moveableRadius, shutdown AI until player is near.
    118.                 return;
    119.             }
    120.            
    121.             if ((distance > attackRange)  (!runAway)  (!runTo)) {
    122.                 enemyCanAttack = false; //the target is too far away to attack
    123.                 MoveTowards (moveToward); //move closer
    124.             } else if ((smoothAttackRangeBuffer)  (distance > attackRange+5.0f)) {
    125.                 smoothAttackRangeBuffer = false;
    126.                 WalkNewPath();
    127.             }else if ((runAway || runTo)  (distance > runDistance)  (!executeBufferState)) {
    128.                 //move in random directions.
    129.                 if (monitorRunTo) {
    130.                     monitorRunTo = false;
    131.                 }
    132.                 if (runAway) {
    133.                     WalkNewPath ();
    134.                 } else {
    135.                     MoveTowards (moveToward);
    136.                 }
    137.             } else if ((runAway || runTo)  (distance < runDistance)  (!executeBufferState)) { //make sure they do not get too close to the target
    138.                 //AHH! RUN AWAY!...  or possibly charge :D
    139.                 enemyCanAttack = false; //can't attack, we're running!
    140.                 if (!monitorRunTo) {
    141.                     executeBufferState = true; //smooth buffer is now active!
    142.                 }
    143.                 walkInRandomDirection = false; //obviously we're no longer moving at random.
    144.                 if (runAway) {
    145.                     MoveTowards (moveAway); //move away
    146.                 } else {
    147.                     MoveTowards (moveToward); //move toward
    148.                 }
    149.             } else if (executeBufferState  ((runAway)  (distance < runBufferDistance)) || ((runTo)  (distance > runBufferDistance))) {
    150.                 //continue to run!
    151.                 if (runAway) {
    152.                     MoveTowards (moveAway); //move away
    153.                 } else {
    154.                     MoveTowards (moveToward); //move toward
    155.                 }
    156.             } else if ((executeBufferState)  (((runAway)  (distance > runBufferDistance)) || ((runTo)  (distance < runBufferDistance)))) {
    157.                 monitorRunTo = true; //make sure that when we have made it to our buffer distance (close to user) we stop the charge until far enough away.
    158.                 executeBufferState = false; //go back to normal activity
    159.             }
    160.  
    161.             //start attacking if close enough
    162.             if ((distance < attackRange) || ((!runAway  !runTo)  (distance < runDistance))) {
    163.                 if (runAway) {
    164.                     smoothAttackRangeBuffer = true;
    165.                 }
    166.                 if (Time.time > lastShotFired + attackTime) {
    167.                     StartCoroutine(Attack());
    168.                 }
    169.             }
    170.            
    171.         } else if ((playerHasBeenSeen)  (!targetIsOutOfSight)  (go)) {
    172.             lostPlayerTimer = Time.time + huntingTimer;
    173.             StartCoroutine(HuntDownTarget(lastVisTargetPos));
    174.         } else if (useWaypoints) {
    175.             Patrol();
    176.         } else if (((!playerHasBeenSeen)  (go))  ((moveableRadius == 0) || (distance < moveableRadius))){
    177.             //the idea here is that the enemy has not yet seen the player, but the player is fairly close while still not visible by the enemy
    178.             //it will move in a random direction continuously altering its direction every 2 seconds until it does see the player.
    179.             WalkNewPath();
    180.         }
    181.     }
    182.    
    183.     //attack stuff...
    184.     IEnumerator Attack() {
    185.         enemyCanAttack = true;
    186.        
    187.         if (!enemyIsAttacking) {
    188.             enemyIsAttacking = true;
    189.             while (enemyCanAttack) {
    190.                 lastShotFired = Time.time;
    191.                 //implement attack variables here
    192.                 yield return new WaitForSeconds(attackTime);
    193.             }
    194.         }
    195.     }
    196.    
    197.    
    198.    
    199.     //----Helper Functions---//
    200.     //verify enemy can see the target
    201.     bool TargetIsInSight () {
    202.         //determine if the enemy should be doing anything other than standing still
    203.         if ((moveableRadius > 0)  (Vector3.Distance(transform.position, target.position) > moveableRadius)) {
    204.             go = false;
    205.         } else {
    206.             go = true;
    207.         }
    208.        
    209.         //then lets make sure the target is within the vision radius we allowed our enemy
    210.         //remember, 0 radius means to ignore this check
    211.         if ((visualRadius > 0)  (Vector3.Distance(transform.position, target.position) > visualRadius)) {
    212.             return false;
    213.         }
    214.        
    215.         //Now check to make sure nothing is blocking the line of sight
    216.         RaycastHit sight;
    217.         if (Physics.Linecast(transform.position, target.position, out sight)) {
    218.             if (!playerHasBeenSeen  sight.transform == target) {
    219.                 playerHasBeenSeen = true;
    220.             }
    221.             return sight.transform == target;
    222.         } else {
    223.             return false;
    224.         }
    225.     }
    226.    
    227.     //target tracking
    228.     IEnumerator HuntDownTarget (Vector3 position) {
    229.         //if this function is called, the enemy has lost sight of the target and must track him down!
    230.         //assuming AI is not too intelligent, they will only move toward his last position, and hope they see him
    231.         //this can be fixed later to update the lastVisTargetPos every couple of seconds to leave some kind of trail
    232.         targetIsOutOfSight = true;
    233.         while (targetIsOutOfSight) {
    234.             Vector3 moveToward = position - transform.position;
    235.             MoveTowards (moveToward);
    236.            
    237.             //check if we found the target yet
    238.             if (TargetIsInSight ()) {
    239.                 targetIsOutOfSight = false;
    240.                 break;
    241.             }
    242.            
    243.             //check to see if we should give up our search
    244.             if (Time.time > lostPlayerTimer) {
    245.                 targetIsOutOfSight = false;
    246.                 playerHasBeenSeen = false;
    247.                 break;
    248.             }
    249.             yield return null;
    250.         }
    251.     }
    252.    
    253.     void Patrol () {
    254.         if (pauseWpControl) {
    255.             return;
    256.         }
    257.         Vector3 destination = CurrentPath();
    258.         Vector3 moveToward = destination - transform.position;
    259.         float distance = Vector3.Distance(transform.position, destination);
    260.         MoveTowards (moveToward);
    261.         if (distance <= 1.5f+floatHeight) {// || (distance < floatHeight+1.5f)) {
    262.             if (pauseAtWaypoints) {
    263.                 if (!pauseWpControl) {
    264.                     pauseWpControl = true;
    265.                     StartCoroutine(WaypointPause());
    266.                 }
    267.             } else {
    268.                 NewPath();
    269.             }
    270.         }
    271.     }
    272.    
    273.     IEnumerator WaypointPause () {
    274.         yield return new WaitForSeconds(Random.Range(pauseMin, pauseMax));
    275.         NewPath();
    276.         pauseWpControl = false;
    277.     }
    278.    
    279.     Vector3 CurrentPath () {
    280.         return waypoints[wpPatrol].position;
    281.     }
    282.    
    283.     void NewPath () {
    284.         if (!wpCountdown) {
    285.             wpPatrol++;
    286.             if (wpPatrol >= waypoints.GetLength(0)) {
    287.                 if (reversePatrol) {
    288.                     wpCountdown = true;
    289.                     wpPatrol -= 2;
    290.                 } else {
    291.                     wpPatrol = 0;
    292.                 }
    293.             }
    294.         } else if (reversePatrol) {
    295.             wpPatrol--;
    296.             if (wpPatrol < 0) {
    297.                 wpCountdown = false;
    298.                 wpPatrol = 1;
    299.             }
    300.         }
    301.     }
    302.    
    303.     //random movement behaviour
    304.     void WalkNewPath () {
    305.         if (!walkInRandomDirection) {
    306.             walkInRandomDirection = true;
    307.             if (!playerHasBeenSeen) {
    308.                 randomDirection = new Vector3(Random.Range(-0.15f,0.15f),0,Random.Range(-0.15f,0.15f));
    309.             } else {
    310.                 randomDirection = new Vector3(Random.Range(-0.5f,0.5f),0,Random.Range(-0.5f,0.5f));
    311.             }
    312.             randomDirectionTimer = Time.time;
    313.         } else if (walkInRandomDirection) {
    314.             MoveTowards (randomDirection);
    315.         }
    316.        
    317.         if ((Time.time - randomDirectionTimer) > 2) {
    318.             //choose a new random direction after 2 seconds
    319.             walkInRandomDirection = false;
    320.         }
    321.     }
    322.    
    323.     //standard movement behaviour
    324.     void MoveTowards (Vector3 direction) {
    325.         direction.y = 0;
    326.         int speed = walkSpeed;
    327.        
    328.         if (walkInRandomDirection) {
    329.             speed = randomSpeed;
    330.         }
    331.        
    332.         if (executeBufferState) {
    333.             speed = runSpeed;
    334.         }
    335.        
    336.         //rotate toward or away from the target
    337.         transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
    338.         transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
    339.  
    340.         //slow down when we are not facing the target
    341.         Vector3 forward = transform.TransformDirection(Vector3.forward);
    342.         float speedModifier = Vector3.Dot(forward, direction.normalized);
    343.         speedModifier = Mathf.Clamp01(speedModifier);
    344.            
    345.         //actually move toward or away from the target
    346.         direction = forward * speed * speedModifier;
    347.         if ((!canFly)  (floatHeight <= 0.0f)) {
    348.             direction.y -= gravity;
    349.         }
    350.         characterController.Move(direction * Time.deltaTime);
    351.     }
    352.    
    353.     //continuous gravity checks
    354.     void MonitorGravity () {
    355.         Vector3 direction = new Vector3(0, 0, 0);
    356.        
    357.         if ((!canFly)  (floatHeight > 0.0f)) {
    358.             //we need to make sure our enemy is floating.. using evil raycasts! bwahahahah!
    359.             if ((estimateElevation)  (estRayTimer > 0.0f)) {
    360.                 if (Time.time > estGravityTimer) {
    361.                     RaycastHit floatCheck;
    362.                     if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) {
    363.                         if (floatCheck.distance < floatHeight-0.5f) {
    364.                             estCheckDirection = 1;
    365.                             estHeight = floatHeight - floatCheck.distance;
    366.                         } else if (floatCheck.distance > floatHeight+0.5f) {
    367.                             estCheckDirection = 2;
    368.                             estHeight = floatCheck.distance - floatHeight;
    369.                         } else {
    370.                             estCheckDirection = 3;
    371.                         }
    372.                     } else {
    373.                         estCheckDirection = 2;
    374.                         estHeight = floatHeight*2;
    375.                     }
    376.                     estGravityTimer = Time.time + estRayTimer;
    377.                 }
    378.            
    379.                 switch(estCheckDirection) {
    380.                     case 1:
    381.                         direction.y += antigravity;
    382.                         estHeight -= direction.y * Time.deltaTime;
    383.                         break;
    384.                     case 2:
    385.                         direction.y -= gravity;
    386.                         estHeight -= direction.y * Time.deltaTime;
    387.                         break;
    388.                     default:
    389.                         //do nothing
    390.                         break;
    391.                 }
    392.                
    393.             } else {
    394.                 RaycastHit floatCheck;
    395.                 if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck, floatHeight+1.0f)) {
    396.                     if (floatCheck.distance < floatHeight) {
    397.                         direction.y += antigravity;
    398.                     }
    399.                 } else {
    400.                     direction.y -= gravity;
    401.                 }
    402.             }
    403.         } else {
    404.             //bird like creature! Again with the evil raycasts! :p
    405.             if ((estimateElevation)  (estRayTimer > 0.0f)) {
    406.                 if (Time.time > estGravityTimer) {
    407.                     RaycastHit floatCheck;
    408.                     if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) {
    409.                         if (floatCheck.distance < floatHeight-0.5f) {
    410.                             estCheckDirection = 1;
    411.                             estHeight = floatHeight - floatCheck.distance;
    412.                         } else if (floatCheck.distance > floatHeight+0.5f) {
    413.                             estCheckDirection = 2;
    414.                             estHeight = floatCheck.distance - floatHeight;
    415.                         } else {
    416.                             estCheckDirection = 3;
    417.                         }
    418.                     }
    419.                     estGravityTimer = Time.time + estRayTimer;
    420.                 }
    421.                    
    422.                 switch(estCheckDirection) {
    423.                     case 1:
    424.                         direction.y += antigravity;
    425.                         estHeight -= direction.y * Time.deltaTime;
    426.                         break;
    427.                     case 2:
    428.                         direction.y -= antigravity;
    429.                         estHeight -= direction.y * Time.deltaTime;
    430.                         break;
    431.                     default:
    432.                         //do nothing
    433.                         break;
    434.                 }
    435.                    
    436.             } else {
    437.                 RaycastHit floatCheck;
    438.                 if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) {
    439.                     if (floatCheck.distance < floatHeight-0.5f) {
    440.                         direction.y += antigravity;
    441.                     } else if (floatCheck.distance > floatHeight+0.5f) {
    442.                         direction.y -= antigravity;
    443.                     }
    444.                 }
    445.             }
    446.         }
    447.        
    448.         if ((!estimateElevation) || ((estimateElevation)  (estHeight >= 0.0f))) {
    449.             characterController.Move(direction * Time.deltaTime);
    450.         }
    451.     }
    452.    
    453. }
     
    Last edited: May 16, 2011
  2. corriedotdev

    corriedotdev

    Joined:
    Sep 1, 2012
    Posts:
    21
    Why are there no replies? This is really nice for a simple ai script. Was just messing around with it. Thanks :D
     
    Eric2241 likes this.
  3. imapie4688

    imapie4688

    Joined:
    Apr 11, 2014
    Posts:
    1
    What king of script form is this? js or C#???
     
  4. tredpro

    tredpro

    Joined:
    Nov 18, 2013
    Posts:
    515
    If it ever starts out with:

    using UnityEngine;

    using System.Collections;



    public class SimpleEnemyAIBehavior : MonoBehaviour {

    I believe it is C# and SimpleEnemyAIBehavior.cs is what you have to call it.
     
    Torktumlaren likes this.
  5. Jaqal

    Jaqal

    Joined:
    Jul 3, 2014
    Posts:
    288
    Tried using this script but I get a few errors I can't pinpoint.
     
  6. Megagamefan100

    Megagamefan100

    Joined:
    Oct 24, 2012
    Posts:
    26
    Here is the version that works for me :)


    Code (CSharp):
    1.  
    2.  
    3. /*
    4.  
    5.         Copyright 2010 Black Storms Studios, LLC.
    6.  
    7.         @Author - Rob Pearson
    8.  
    9.         @Date - November 2010
    10.  
    11.         @Contact - RIPearson@BlackStormsStudios.com
    12.  
    13.         @Script -
    14.  
    15.         @Connections - requires CharacterController attached to enemy.
    16.  
    17.         @TODO -
    18.  
    19. */
    20.  
    21.  
    22. using UnityEngine;
    23.  
    24. using System.Collections;
    25.  
    26.  
    27. public class AI : MonoBehaviour {
    28.  
    29.    
    30.  
    31.     //Inspector initiated variables. Defaults are set for ease of use.
    32.  
    33.     public bool on = true; //Is the AI active? this can be used to place pre-set enemies in you scene.
    34.  
    35.     public bool canFly = false; //Flying alters float behavior to ignore gravity. The enemy will fly up or down only to sustain floatHeight level.
    36.  
    37.     public float floatHeight = 0.0f; //If it can fly/hover, you need to let the AI know how high off the ground it should be.
    38.  
    39.     public bool runAway = false; //Is it the goal of this AI to keep it's distance? If so, it needs to have runaway active.
    40.  
    41.     public bool runTo = false; //Opposite to runaway, within a certain distance, the enemy will run toward the target.
    42.  
    43.     public float runDistance = 25.0f; //If the enemy should keep its distance, or charge in, at what point should they begin to run?
    44.  
    45.     public float runBufferDistance = 50.0f; //Smooth AI buffer. How far apart does AI/Target need to be before the run reason is ended.
    46.  
    47.     public int walkSpeed = 10; //Standard movement speed.
    48.  
    49.     public int runSpeed = 15; //Movement speed if it needs to run.
    50.  
    51.     public int randomSpeed = 10; //Movement speed if the AI is moving in random directions.
    52.  
    53.     public float rotationSpeed = 20.0f; //Rotation during movement modifier. If AI starts spinning at random, increase this value. (First check to make sure it's not due to visual radius limitations)
    54.  
    55.     public float visualRadius = 100.0f; //How close does the player need to be to be seen by the enemy? Set to 0 to remove this limitation.
    56.  
    57.     public float moveableRadius = 200.0f; //If the player is too far away, the AI will auto-matically shut down. Set to 0 to remove this limitation.
    58.  
    59.     public float attackRange = 10.0f; //How close does the enemy need to be in order to attack?
    60.  
    61.     public float attackTime = 0.50f; //How frequent or fast an enemy can attack (cool down time).
    62.  
    63.     public bool useWaypoints = false; //If true, the AI will make use of the waypoints assigned to it until over-ridden by another functionality.
    64.  
    65.     public bool reversePatrol = true; //if true, patrol units will walk forward and backward along their patrol.
    66.  
    67.     public Transform[] waypoints; //define a set path for them to follow.
    68.  
    69.     public bool pauseAtWaypoints = false; //if true, patrol units will pause momentarily at each waypoint as they reach them.
    70.  
    71.     public float pauseMin = 1.0f; //If pauseAtWaypoints is true, the unit will pause momentarily for minmum of this time.
    72.  
    73.     public float pauseMax = 3.0f; //If pauseAtWaypoints is true, the unit will pause momentarily formaximum of this time.
    74.  
    75.     public float huntingTimer = 5.0f; //Search for player timer in seconds. Minimum of 0.1
    76.  
    77.     public bool estimateElevation = false; //This implements a pause between raycasts for heights and guestimates the need to move up/down in height based on the previous raycast.
    78.  
    79.     public float estRayTimer = 1.0f; //The amount of time in seconds between raycasts for gravity and elevation checks.
    80.  
    81.     public bool requireTarget = true; //Waypoint ONLY functionality (still can fly and hover).
    82.  
    83.     public Transform target; //The target, or whatever the AI is looking for.
    84.  
    85.    
    86.  
    87.    
    88.  
    89.     //private script handled variables
    90.  
    91.     private bool initialGo = false; //AI cannot function until it is initialized.
    92.  
    93.     private bool go = true; //An on/off override variable
    94.  
    95.     private Vector3 lastVisTargetPos; //Monitor target position if we lose sight of target. provides semi-intelligent AI.
    96.  
    97.     CharacterController characterController; //CC used for enemy movement and etc.
    98.  
    99.     private bool playerHasBeenSeen = false; //An enhancement to how the AI functions prior to visibly seeing the target. Brings AI to life when target is close, but not visible.
    100.  
    101.     private bool enemyCanAttack = false; //Used to determine if the enemy is within range to attack, regardless of moving or not.
    102.  
    103.     private bool enemyIsAttacking = false; //An attack interuption method.
    104.  
    105.     private bool executeBufferState = false; //Smooth AI buffer for runAway AI. Also used as a speed control variable.
    106.  
    107.     private bool walkInRandomDirection = false; //Speed control variable.
    108.  
    109.     private float lastShotFired; //Used in conjuction with attackTime to monitor attack durations.
    110.  
    111.     private float lostPlayerTimer; //Used for hunting down the player.
    112.  
    113.     private bool targetIsOutOfSight; //Player tracking overload prevention. Makes sure we do not call the same coroutines over and over.
    114.  
    115.     private Vector3 randomDirection; //Random movement behaviour setting.
    116.  
    117.     private float randomDirectionTimer; //Random movement behaviour tracking.
    118.  
    119.     private float gravity = 20.0f; //force of gravity pulling the enemy down.
    120.  
    121.     private float antigravity = 2.0f; //force at which floating/flying enemies repel
    122.  
    123.     private float estHeight = 0.0f; //floating/flying creatures using estimated elevation use this to estimate height necessities and gravity impacts.
    124.  
    125.     private float estGravityTimer = 0.0f; //floating/flying creatures using estimated elevation will use this to actually monitor time values.
    126.  
    127.     private int estCheckDirection = 0; //used to determine if AI is falling or not when estimating elevation.
    128.  
    129.     private bool wpCountdown = false; //used to determine if we're moving forward or backward through the waypoints.
    130.  
    131.     private bool monitorRunTo = false; //when AI is set to runTo, they will charge in, and then not charge again to after far enough away.
    132.  
    133.     private int wpPatrol = 0; //determines what waypoint we are heading toward.
    134.  
    135.     private bool pauseWpControl; //makes sure unit pauses appropriately.
    136.  
    137.     private bool smoothAttackRangeBuffer = false; //for runAway AI to not be so messed up by their visual radius and attack range.
    138.  
    139.    
    140.  
    141.    
    142.  
    143.  
    144.     //---Starting/Initializing functions---//
    145.  
    146.     void Start() {
    147.  
    148.         StartCoroutine(Initialize()); //co-routine is used incase you need to interupt initiialization until something else is done.
    149.  
    150.     }
    151.  
    152.    
    153.  
    154.     IEnumerator Initialize() {
    155.  
    156.         if ((estimateElevation) && (floatHeight > 0.0f)) {
    157.  
    158.             estGravityTimer = Time.time;
    159.  
    160.         }
    161.  
    162.         characterController = gameObject.GetComponent<CharacterController>();
    163.  
    164.         initialGo = true;
    165.  
    166.         yield return null;
    167.  
    168.     }
    169.  
    170.    
    171.  
    172.    
    173.  
    174.    
    175.  
    176.     //---Main Functionality---//
    177.  
    178.     void Update () {
    179.  
    180.         if (!on || !initialGo) {
    181.  
    182.             return;
    183.  
    184.         } else {
    185.  
    186.             AIFunctionality();
    187.  
    188.         }
    189.  
    190.     }
    191.  
    192.    
    193.  
    194.     void AIFunctionality() {
    195.  
    196.         if ((!target) && (requireTarget)) {
    197.  
    198.             return; //if no target was set and we require one, AI will not function.
    199.  
    200.         }
    201.  
    202.        
    203.  
    204.         //Functionality Updates
    205.  
    206.         lastVisTargetPos = target.position; //Target tracking method for semi-intelligent AI
    207.  
    208.         Vector3 moveToward = lastVisTargetPos - transform.position; //Used to face the AI in the direction of the target
    209.  
    210.         Vector3 moveAway = transform.position - lastVisTargetPos; //Used to face the AI away from the target when running away
    211.  
    212.         float distance = Vector3.Distance(transform.position, target.position);
    213.  
    214.        
    215.  
    216.         if (go) {
    217.  
    218.             MonitorGravity();
    219.  
    220.         }
    221.  
    222.        
    223.  
    224.         if (!requireTarget) {
    225.  
    226.             //waypoint only functionality
    227.  
    228.             Patrol();
    229.  
    230.         } else if (TargetIsInSight ()) {
    231.  
    232.             if (!go) { //useWaypoints is false and the player has exceeded moveableRadius, shutdown AI until player is near.
    233.  
    234.                 return;
    235.  
    236.             }
    237.  
    238.            
    239.  
    240.             if ((distance > attackRange) && (!runAway) && (!runTo)) {
    241.  
    242.                 enemyCanAttack = false; //the target is too far away to attack
    243.  
    244.                 MoveTowards (moveToward); //move closer
    245.  
    246.             } else if ((smoothAttackRangeBuffer) && (distance > attackRange+5.0f)) {
    247.  
    248.                 smoothAttackRangeBuffer = false;
    249.  
    250.                 WalkNewPath();
    251.  
    252.             }else if ((runAway || runTo) && (distance > runDistance) && (!executeBufferState)) {
    253.  
    254.                 //move in random directions.
    255.  
    256.                 if (monitorRunTo) {
    257.  
    258.                     monitorRunTo = false;
    259.  
    260.                 }
    261.  
    262.                 if (runAway) {
    263.  
    264.                     WalkNewPath ();
    265.  
    266.                 } else {
    267.  
    268.                     MoveTowards (moveToward);
    269.  
    270.                 }
    271.  
    272.             } else if ((runAway || runTo) && (distance < runDistance) && (!executeBufferState)) { //make sure they do not get too close to the target
    273.  
    274.                 //AHH! RUN AWAY!...  or possibly charge :D
    275.  
    276.                 enemyCanAttack = false; //can't attack, we're running!
    277.  
    278.                 if (!monitorRunTo) {
    279.  
    280.                     executeBufferState = true; //smooth buffer is now active!
    281.  
    282.                 }
    283.  
    284.                 walkInRandomDirection = false; //obviously we're no longer moving at random.
    285.  
    286.                 if (runAway) {
    287.  
    288.                     MoveTowards (moveAway); //move away
    289.  
    290.                 } else {
    291.  
    292.                     MoveTowards (moveToward); //move toward
    293.  
    294.                 }
    295.  
    296.             } else if (executeBufferState && ((runAway) && (distance < runBufferDistance)) || ((runTo) && (distance > runBufferDistance))) {
    297.  
    298.                 //continue to run!
    299.  
    300.                 if (runAway) {
    301.  
    302.                     MoveTowards (moveAway); //move away
    303.  
    304.                 } else {
    305.  
    306.                     MoveTowards (moveToward); //move toward
    307.  
    308.                 }
    309.  
    310.             } else if ((executeBufferState) && (((runAway) && (distance > runBufferDistance)) || ((runTo) && (distance < runBufferDistance)))) {
    311.  
    312.                 monitorRunTo = true; //make sure that when we have made it to our buffer distance (close to user) we stop the charge until far enough away.
    313.  
    314.                 executeBufferState = false; //go back to normal activity
    315.  
    316.             }
    317.  
    318.  
    319.             //start attacking if close enough
    320.  
    321.             if ((distance < attackRange) || ((!runAway && !runTo) && (distance < runDistance))) {
    322.  
    323.                 if (runAway) {
    324.  
    325.                     smoothAttackRangeBuffer = true;
    326.  
    327.                 }
    328.  
    329.                 if (Time.time > lastShotFired + attackTime) {
    330.  
    331.                     StartCoroutine(Attack());
    332.  
    333.                 }
    334.  
    335.             }
    336.  
    337.            
    338.  
    339.         } else if ((playerHasBeenSeen) && (!targetIsOutOfSight) && (go)) {
    340.  
    341.             lostPlayerTimer = Time.time + huntingTimer;
    342.  
    343.             StartCoroutine(HuntDownTarget(lastVisTargetPos));
    344.  
    345.         } else if (useWaypoints) {
    346.  
    347.             Patrol();
    348.  
    349.         } else if (((!playerHasBeenSeen) && (go)) && ((moveableRadius == 0) || (distance < moveableRadius))){
    350.  
    351.             //the idea here is that the enemy has not yet seen the player, but the player is fairly close while still not visible by the enemy
    352.  
    353.             //it will move in a random direction continuously altering its direction every 2 seconds until it does see the player.
    354.  
    355.             WalkNewPath();
    356.  
    357.         }
    358.  
    359.     }
    360.  
    361.    
    362.  
    363.     //attack stuff...
    364.  
    365.     IEnumerator Attack() {
    366.  
    367.         enemyCanAttack = true;
    368.  
    369.        
    370.  
    371.         if (!enemyIsAttacking) {
    372.  
    373.             enemyIsAttacking = true;
    374.  
    375.             while (enemyCanAttack) {
    376.  
    377.                 lastShotFired = Time.time;
    378.  
    379.                 //implement attack variables here
    380.  
    381.                 yield return new WaitForSeconds(attackTime);
    382.  
    383.             }
    384.  
    385.         }
    386.  
    387.     }
    388.  
    389.    
    390.  
    391.    
    392.  
    393.    
    394.  
    395.     //----Helper Functions---//
    396.  
    397.     //verify enemy can see the target
    398.  
    399.     bool TargetIsInSight () {
    400.  
    401.         //determine if the enemy should be doing anything other than standing still
    402.  
    403.         if ((moveableRadius > 0) && (Vector3.Distance(transform.position, target.position) > moveableRadius)) {
    404.  
    405.             go = false;
    406.  
    407.         } else {
    408.  
    409.             go = true;
    410.  
    411.         }
    412.  
    413.        
    414.  
    415.         //then lets make sure the target is within the vision radius we allowed our enemy
    416.  
    417.         //remember, 0 radius means to ignore this check
    418.  
    419.         if ((visualRadius > 0) && (Vector3.Distance(transform.position, target.position) > visualRadius)) {
    420.  
    421.             return false;
    422.  
    423.         }
    424.  
    425.        
    426.  
    427.         //Now check to make sure nothing is blocking the line of sight
    428.  
    429.         RaycastHit sight;
    430.  
    431.         if (Physics.Linecast(transform.position, target.position, out sight)) {
    432.  
    433.             if (!playerHasBeenSeen && sight.transform == target) {
    434.  
    435.                 playerHasBeenSeen = true;
    436.  
    437.             }
    438.  
    439.             return sight.transform == target;
    440.  
    441.         } else {
    442.  
    443.             return false;
    444.  
    445.         }
    446.  
    447.     }
    448.  
    449.    
    450.  
    451.     //target tracking
    452.  
    453.     IEnumerator HuntDownTarget (Vector3 position) {
    454.  
    455.         //if this function is called, the enemy has lost sight of the target and must track him down!
    456.  
    457.         //assuming AI is not too intelligent, they will only move toward his last position, and hope they see him
    458.  
    459.         //this can be fixed later to update the lastVisTargetPos every couple of seconds to leave some kind of trail
    460.  
    461.         targetIsOutOfSight = true;
    462.  
    463.         while (targetIsOutOfSight) {
    464.  
    465.             Vector3 moveToward = position - transform.position;
    466.  
    467.             MoveTowards (moveToward);
    468.  
    469.            
    470.  
    471.             //check if we found the target yet
    472.  
    473.             if (TargetIsInSight ()) {
    474.  
    475.                 targetIsOutOfSight = false;
    476.  
    477.                 break;
    478.  
    479.             }
    480.  
    481.            
    482.  
    483.             //check to see if we should give up our search
    484.  
    485.             if (Time.time > lostPlayerTimer) {
    486.  
    487.                 targetIsOutOfSight = false;
    488.  
    489.                 playerHasBeenSeen = false;
    490.  
    491.                 break;
    492.  
    493.             }
    494.  
    495.             yield return null;
    496.  
    497.         }
    498.  
    499.     }
    500.  
    501.    
    502.  
    503.     void Patrol () {
    504.  
    505.         if (pauseWpControl) {
    506.  
    507.             return;
    508.  
    509.         }
    510.  
    511.         Vector3 destination = CurrentPath();
    512.  
    513.         Vector3 moveToward = destination - transform.position;
    514.  
    515.         float distance = Vector3.Distance(transform.position, destination);
    516.  
    517.         MoveTowards (moveToward);
    518.  
    519.         if (distance <= 1.5f+floatHeight) {// || (distance < floatHeight+1.5f)) {
    520.  
    521.             if (pauseAtWaypoints) {
    522.  
    523.                 if (!pauseWpControl) {
    524.  
    525.                     pauseWpControl = true;
    526.  
    527.                     StartCoroutine(WaypointPause());
    528.  
    529.                 }
    530.  
    531.             } else {
    532.  
    533.                 NewPath();
    534.  
    535.             }
    536.  
    537.         }
    538.  
    539.     }
    540.  
    541.    
    542.  
    543.     IEnumerator WaypointPause () {
    544.  
    545.         yield return new WaitForSeconds(Random.Range(pauseMin, pauseMax));
    546.  
    547.         NewPath();
    548.  
    549.         pauseWpControl = false;
    550.  
    551.     }
    552.  
    553.    
    554.  
    555.     Vector3 CurrentPath () {
    556.  
    557.         return waypoints[wpPatrol].position;
    558.  
    559.     }
    560.  
    561.    
    562.  
    563.     void NewPath () {
    564.  
    565.         if (!wpCountdown) {
    566.  
    567.             wpPatrol++;
    568.  
    569.             if (wpPatrol >= waypoints.GetLength(0)) {
    570.  
    571.                 if (reversePatrol) {
    572.  
    573.                     wpCountdown = true;
    574.  
    575.                     wpPatrol -= 2;
    576.  
    577.                 } else {
    578.  
    579.                     wpPatrol = 0;
    580.  
    581.                 }
    582.  
    583.             }
    584.  
    585.         } else if (reversePatrol) {
    586.  
    587.             wpPatrol--;
    588.  
    589.             if (wpPatrol < 0) {
    590.  
    591.                 wpCountdown = false;
    592.  
    593.                 wpPatrol = 1;
    594.  
    595.             }
    596.  
    597.         }
    598.  
    599.     }
    600.  
    601.    
    602.  
    603.     //random movement behaviour
    604.  
    605.     void WalkNewPath () {
    606.  
    607.         if (!walkInRandomDirection) {
    608.  
    609.             walkInRandomDirection = true;
    610.  
    611.             if (!playerHasBeenSeen) {
    612.  
    613.                 randomDirection = new Vector3(Random.Range(-0.15f,0.15f),0,Random.Range(-0.15f,0.15f));
    614.  
    615.             } else {
    616.  
    617.                 randomDirection = new Vector3(Random.Range(-0.5f,0.5f),0,Random.Range(-0.5f,0.5f));
    618.  
    619.             }
    620.  
    621.             randomDirectionTimer = Time.time;
    622.  
    623.         } else if (walkInRandomDirection) {
    624.  
    625.             MoveTowards (randomDirection);
    626.  
    627.         }
    628.  
    629.        
    630.  
    631.         if ((Time.time - randomDirectionTimer) > 2) {
    632.  
    633.             //choose a new random direction after 2 seconds
    634.  
    635.             walkInRandomDirection = false;
    636.  
    637.         }
    638.  
    639.     }
    640.  
    641.    
    642.  
    643.     //standard movement behaviour
    644.  
    645.     void MoveTowards (Vector3 direction) {
    646.  
    647.         direction.y = 0;
    648.  
    649.         int speed = walkSpeed;
    650.  
    651.        
    652.  
    653.         if (walkInRandomDirection) {
    654.  
    655.             speed = randomSpeed;
    656.  
    657.         }
    658.  
    659.        
    660.  
    661.         if (executeBufferState) {
    662.  
    663.             speed = runSpeed;
    664.  
    665.         }
    666.  
    667.        
    668.  
    669.         //rotate toward or away from the target
    670.  
    671.         transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
    672.  
    673.         transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
    674.  
    675.  
    676.         //slow down when we are not facing the target
    677.  
    678.         Vector3 forward = transform.TransformDirection(Vector3.forward);
    679.  
    680.         float speedModifier = Vector3.Dot(forward, direction.normalized);
    681.  
    682.         speedModifier = Mathf.Clamp01(speedModifier);
    683.  
    684.            
    685.  
    686.         //actually move toward or away from the target
    687.  
    688.         direction = forward * speed * speedModifier;
    689.  
    690.         if ((!canFly) && (floatHeight <= 0.0f)) {
    691.  
    692.             direction.y -= gravity;
    693.  
    694.         }
    695.  
    696.         characterController.Move(direction * Time.deltaTime);
    697.  
    698.     }
    699.  
    700.    
    701.  
    702.     //continuous gravity checks
    703.  
    704.     void MonitorGravity () {
    705.  
    706.         Vector3 direction = new Vector3(0, 0, 0);
    707.  
    708.        
    709.  
    710.         if ((!canFly) && (floatHeight > 0.0f)) {
    711.  
    712.             //we need to make sure our enemy is floating.. using evil raycasts! bwahahahah!
    713.  
    714.             if ((estimateElevation) && (estRayTimer > 0.0f)) {
    715.  
    716.                 if (Time.time > estGravityTimer) {
    717.  
    718.                     RaycastHit floatCheck;
    719.  
    720.                     if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) {
    721.  
    722.                         if (floatCheck.distance < floatHeight-0.5f) {
    723.  
    724.                             estCheckDirection = 1;
    725.  
    726.                             estHeight = floatHeight - floatCheck.distance;
    727.  
    728.                         } else if (floatCheck.distance > floatHeight+0.5f) {
    729.  
    730.                             estCheckDirection = 2;
    731.  
    732.                             estHeight = floatCheck.distance - floatHeight;
    733.  
    734.                         } else {
    735.  
    736.                             estCheckDirection = 3;
    737.  
    738.                         }
    739.  
    740.                     } else {
    741.  
    742.                         estCheckDirection = 2;
    743.  
    744.                         estHeight = floatHeight*2;
    745.  
    746.                     }
    747.  
    748.                     estGravityTimer = Time.time + estRayTimer;
    749.  
    750.                 }
    751.  
    752.            
    753.  
    754.                 switch(estCheckDirection) {
    755.  
    756.                     case 1:
    757.  
    758.                         direction.y += antigravity;
    759.  
    760.                         estHeight -= direction.y * Time.deltaTime;
    761.  
    762.                         break;
    763.  
    764.                     case 2:
    765.  
    766.                         direction.y -= gravity;
    767.  
    768.                         estHeight -= direction.y * Time.deltaTime;
    769.  
    770.                         break;
    771.  
    772.                     default:
    773.  
    774.                         //do nothing
    775.  
    776.                         break;
    777.  
    778.                 }
    779.  
    780.                
    781.  
    782.             } else {
    783.  
    784.                 RaycastHit floatCheck;
    785.  
    786.                 if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck, floatHeight+1.0f)) {
    787.  
    788.                     if (floatCheck.distance < floatHeight) {
    789.  
    790.                         direction.y += antigravity;
    791.  
    792.                     }
    793.  
    794.                 } else {
    795.  
    796.                     direction.y -= gravity;
    797.  
    798.                 }
    799.  
    800.             }
    801.  
    802.         } else {
    803.  
    804.             //bird like creature! Again with the evil raycasts! :p
    805.  
    806.             if ((estimateElevation) && (estRayTimer > 0.0f)) {
    807.  
    808.                 if (Time.time > estGravityTimer) {
    809.  
    810.                     RaycastHit floatCheck;
    811.  
    812.                     if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) {
    813.  
    814.                         if (floatCheck.distance < floatHeight-0.5f) {
    815.  
    816.                             estCheckDirection = 1;
    817.  
    818.                             estHeight = floatHeight - floatCheck.distance;
    819.  
    820.                         } else if (floatCheck.distance > floatHeight+0.5f) {
    821.  
    822.                             estCheckDirection = 2;
    823.  
    824.                             estHeight = floatCheck.distance - floatHeight;
    825.  
    826.                         } else {
    827.  
    828.                             estCheckDirection = 3;
    829.  
    830.                         }
    831.  
    832.                     }
    833.  
    834.                     estGravityTimer = Time.time + estRayTimer;
    835.  
    836.                 }
    837.  
    838.                    
    839.  
    840.                 switch(estCheckDirection) {
    841.  
    842.                     case 1:
    843.  
    844.                         direction.y += antigravity;
    845.  
    846.                         estHeight -= direction.y * Time.deltaTime;
    847.  
    848.                         break;
    849.  
    850.                     case 2:
    851.  
    852.                         direction.y -= antigravity;
    853.  
    854.                         estHeight -= direction.y * Time.deltaTime;
    855.  
    856.                         break;
    857.  
    858.                     default:
    859.  
    860.                         //do nothing
    861.  
    862.                         break;
    863.  
    864.                 }
    865.  
    866.                    
    867.  
    868.             } else {
    869.  
    870.                 RaycastHit floatCheck;
    871.  
    872.                 if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) {
    873.  
    874.                     if (floatCheck.distance < floatHeight-0.5f) {
    875.  
    876.                         direction.y += antigravity;
    877.  
    878.                     } else if (floatCheck.distance > floatHeight+0.5f) {
    879.  
    880.                         direction.y -= antigravity;
    881.  
    882.                     }
    883.  
    884.                 }
    885.  
    886.             }
    887.  
    888.         }
    889.  
    890.        
    891.  
    892.         if ((!estimateElevation) || ((estimateElevation) && (estHeight >= 0.0f))) {
    893.  
    894.             characterController.Move(direction * Time.deltaTime);
    895.  
    896.         }
    897.  
    898.     }
    899.  
    900.    
    901.  
    902. }
    903.  
     
    BABOONATIC, Threeyes and Jaqal like this.
  7. Jaqal

    Jaqal

    Joined:
    Jul 3, 2014
    Posts:
    288
    @Megagamefan100 This script starts up fine and the enemies will walk around but for some reason they will never target my player. I have my player object in the target transform slot. Dk what could be causing this.

    Edit: I just had to add a collider to my character and now it works great. Now i'm trying to figure out how to set this up with navmesh and ill be set!
     
    Last edited: Jul 29, 2014
  8. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    just an FYI... your title says free script but the first line in it says Copy Right info... I'm confused.
     
    Undying54 and keenanwoodall like this.
  9. keenanwoodall

    keenanwoodall

    Joined:
    May 30, 2014
    Posts:
    598
    I was wondering about that too. I'm always so worried about stuff like that!
     
    Undying54 likes this.
  10. Megagamefan100

    Megagamefan100

    Joined:
    Oct 24, 2012
    Posts:
    26
    ok
     
  11. Megagamefan100

    Megagamefan100

    Joined:
    Oct 24, 2012
    Posts:
    26
    Oh and I am remaking this script to do a lot more :)
     
  12. MahaGaming

    MahaGaming

    Joined:
    Feb 25, 2014
    Posts:
    82
    is this script ok to use then? i dont want to get in trouble.
     
  13. Ayato-Naoi

    Ayato-Naoi

    Joined:
    Mar 17, 2013
    Posts:
    2
    So, if I may ask, when you redo the script, will it have something of animations within in? For example, when the enemy charges the player, it'll play a run animation?
     
    Hawk0077 likes this.
  14. hayesjl77

    hayesjl77

    Joined:
    Jan 3, 2017
    Posts:
    6
    so this is an older post but so far the better of the random AI movements ive found. The issue im having is no matter what the setting the first few mins they seem to be hunting the target then they all just scatter and move away never to be seen again. Ive set visual range high ive set hunt timer high ive set required targets just nothing seems to keep them in attack mode. Im using this for a space shooter so the ships just fly off into infinity.

    Second non scrip related how do I spawn a copy of a prefab without killing the prefab which kills the spawner? Ive made an empty object named spawncontroller and added an empty child to that named spawner. Ive set it a ways out from the base and set my spawns from there. no matter how I set it up it kills the original clone and then i start getting errors the object is not there to spawn from.

    Thanks in advance.
     
  15. Hemalab

    Hemalab

    Joined:
    Feb 6, 2016
    Posts:
    5
    i cant get the enemy to attack me..
    ive added the player prefab to the script

    the script is on the enemy
    i have a collider
    ridgedbody and char controller
     
  16. tredpro

    tredpro

    Joined:
    Nov 18, 2013
    Posts:
    515
    Do you have a collider on your character...
     
  17. SoloTree

    SoloTree

    Joined:
    Jul 2, 2017
    Posts:
    4
    OMG TY SO MUCH! I COULDN'T BE STUFFED WRITING AN AI SCRIPT AND THEN I FOUND THIS! TYTYTYTYTYYTY
     
  18. Vampyr_Engel

    Vampyr_Engel

    Joined:
    Dec 17, 2014
    Posts:
    449
    I have a very crude script of A.I which can be friendly or enemy that works on a sphere but I want it to get in and out of vehicles and be able to stop and take cover and shoot guns can anyone help please?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class EnemyAI: MonoBehaviour {
    5.     Vector3 Enemy_AImoveAmount;
    6.     Rigidbody Enemy_AIRigidbody;
    7.     Transform tr_Player;
    8.     public LayerMask groundedMask;
    9.     float f_RotSpeed=60.0f,f_MoveSpeed = 40.0f;
    10.     public float walkSpeed = 40;
    11.    
    12.     // Use this for initialization
    13.     void Start () {
    14.        
    15.         tr_Player = GameObject.FindGameObjectWithTag ("Player").transform; }
    16.        
    17.        
    18.     // Update is called once per frame
    19.     void Update () {
    20.         /* Look at Player*/
    21.         transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (tr_Player.position - transform.position), f_RotSpeed * Time.deltaTime);
    22.        
    23.         /* Move at Player*/
    24.         transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
    25.          }
    26.     void FixedUpdate() {
    27.         // Apply movement to rigidbody
    28.         Vector3 localMove = transform.TransformDirection(Enemy_AImoveAmount) * Time.fixedDeltaTime;
    29.         GetComponent<Rigidbody>();Enemy_AIRigidbody.MovePosition(GetComponent<Rigidbody>().position + localMove);
    30.     }
    31. }
     
    rogop likes this.
  19. mattis89

    mattis89

    Joined:
    Jan 10, 2017
    Posts:
    1,151
    they dont move at all.. nothing happends... waypoiints ARE TICKED.
     
  20. timisahappydude

    timisahappydude

    Joined:
    Aug 30, 2018
    Posts:
    1
    Hi I really like the script. Everything that i have tried in a couple of minutes has worked fine. Ill go through the finer points when i sit down tomorrow and let you know what i find.
     
  21. paulson_101

    paulson_101

    Joined:
    Mar 21, 2018
    Posts:
    6
    So I added this script to my 2D Sprite. And nothing happens. No compiler errors anything, any idea?

    Capture.PNG
     
  22. naiemali1171987

    naiemali1171987

    Joined:
    Sep 19, 2018
    Posts:
    3
    Literally nothing is show at all in the inspector can someone please help me.
     
  23. Lynestro

    Lynestro

    Joined:
    Jun 26, 2017
    Posts:
    1
    Guys, the script's 9 years old. It's not gonna work.
     
    mattis89 likes this.
  24. Suvankar017

    Suvankar017

    Joined:
    Sep 16, 2018
    Posts:
    1
    C#
     
  25. unity_9Udemw6xsNCi5A

    unity_9Udemw6xsNCi5A

    Joined:
    May 20, 2019
    Posts:
    2
    Free means you can use it without charge. Copyright means you can't claim it as your own work.
     
    sfrk246, moosesnWoop and leftshoe18 like this.
  26. brentnicholas2011

    brentnicholas2011

    Joined:
    Oct 8, 2019
    Posts:
    1
    So what did you find did it work?
     
  27. dabdaddydarko

    dabdaddydarko

    Joined:
    Jul 17, 2018
    Posts:
    14
    so I tried the script(thank you btw) but it only makes my enemy run to the lowest portion of the map
     
  28. davidnibi

    davidnibi

    Joined:
    Dec 19, 2012
    Posts:
    426
    It won't work in 2D.

    This should still work fine even in v2019. I got it a few years ago and heavily modified it but it worked like a dream.
    To test it, attach it to a cube with a character controller, and then create another cube and link this to the target of the script.

    You need a character controller on the thing you are attaching it to.

    You also need a box collider on your target - a sphere, capsule, etc won't do it. The box collider needs to intersect or be flat on the 'floor'.

    You need a target, but you can make these ignore if null and edit the parts that require these.

    If you're finding it's not finding the target, it may be because your player (the target) is attaching something it needs (like a BoxCollider added in code) later than the script is looking for it (through lateupdate or awake or something).
    Something like this should fix it:
    Code (CSharp):
    1. if(target)
    2. {
    3. //get target
    4. }
    If you want an enemy to follow you regardless for ease, just assign your player as a waypoint.
    Adding further dependency on character controller can increase it's usefulness, like character controller velocity = 0 turn round 90 - 180 degrees for crude pathfinding abilities.

     
    Last edited: Feb 12, 2020
  29. unity_ctFXCNp5IjAk5A

    unity_ctFXCNp5IjAk5A

    Joined:
    Feb 14, 2020
    Posts:
    1
    I was going to use Megagamefan100's script for a little project (Using Unity 2018.4.12f1) when I ran into an error CS1061, where there was an issue with the 'CharacterController' and 'Move.' I have used this script on another project and it worked just fine with no compiler errors. Any help/advice would be much appreciated. Thanks.
     
  30. light8888

    light8888

    Joined:
    Jul 13, 2020
    Posts:
    1
    thank you brother, good day!.
     
  31. Roelant2

    Roelant2

    Joined:
    Dec 12, 2020
    Posts:
    1
    theres 60 errors
     
  32. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Please don't reply to 10-year-old post threads with content-less three-word sentences. Nobody here reads minds.

    Start your own thread: it's free and it is the forum rules.

    BEFORE YOU POST, read this: How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    How to understand errors in general:

    https://forum.unity.com/threads/ass...3-syntax-error-expected.1039702/#post-6730855

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
Thread Status:
Not open for further replies.