Search Unity

AI Pathfinding Tutorial FPS1.36 Reference code and Project Download. ETeeskiTutorials

Discussion in 'Community Learning & Teaching' started by eteeski, Apr 3, 2012.

  1. eteeski

    eteeski

    Joined:
    Feb 2, 2010
    Posts:
    476
    Here's the scripts that were used in FPS1.36
    If you haven't seen my tutorials yet, please check them out if you're interested in making a first person shooter or AI pathfinding.
    youtube.com/eteeskitutorials


    EnemyMovementScript:
    Code (csharp):
    1.  
    2. var currentCell : GameObject;
    3. var playerMovementScript : PlayerMovementScript;
    4. var playerTransform : Transform;
    5. var playerCell : GameObject;
    6. var goalDoor : GameObject;
    7. var shortestPathSoFar : float;
    8. @HideInInspector
    9. var waitToStart : int = 5;
    10. var currentMoveSpeed : float = 5;
    11.  
    12. var randomizedCourse : boolean = false;
    13. var randomizeCourseVector : Vector3;
    14. var calculatedNewRandomizeCourseVector : boolean;
    15.  
    16. function Awake ()
    17. {
    18.     shortestPathSoFar = Mathf.Infinity;
    19.     playerMovementScript = GameObject.FindWithTag("Player").GetComponent(PlayerMovementScript);
    20.     playerTransform = GameObject.FindWithTag("Player").transform;
    21.     waitToStart = 5;
    22.     randomizeCourseVector = transform.position;
    23. }
    24.  
    25. function Update ()
    26. {
    27.     if (waitToStart <= 0)
    28.     {
    29.         playerCell = playerMovementScript.currentCell;
    30.         for (var doorCheckingNow : GameObject in currentCell.GetComponent(AIpathCellScript).doors)
    31.         {
    32.             for (var i : int = 0; i <= doorCheckingNow.GetComponent(AIpathDoorScript).cells.length - 1; i++)
    33.             {
    34.                 if (doorCheckingNow.GetComponent(AIpathDoorScript).cells[i] == playerCell)
    35.                 if (doorCheckingNow.GetComponent(AIpathDoorScript).doorsToCells[i] < shortestPathSoFar)
    36.                 {
    37.                     goalDoor = doorCheckingNow;
    38.                     shortestPathSoFar = doorCheckingNow.GetComponent(AIpathDoorScript).doorsToCells[i];
    39.                 }
    40.             }
    41.         }
    42.         shortestPathSoFar = Mathf.Infinity;
    43.     }
    44.     waitToStart -= 1;
    45.    
    46.     if (!calculatedNewRandomizeCourseVector)
    47.     {
    48.         randomizeCourseVector = FindRandomSpotInCurrentCell();
    49.         calculatedNewRandomizeCourseVector = true;
    50.     }
    51.    
    52.     if (goalDoor)
    53.     if (!goalDoor.GetComponent(AIpathDoorScript).doorOpen)
    54.         goalDoor = null;
    55.    
    56.     if (currentCell != playerCell || playerCell == null)
    57.     {
    58.         if (randomizedCourse)
    59.             transform.position += (goalDoor.transform.position - transform.position).normalized * currentMoveSpeed * Time.deltaTime;
    60.         if (!randomizedCourse)
    61.         {
    62.             transform.position += (randomizeCourseVector - transform.position).normalized * currentMoveSpeed * Time.deltaTime;
    63.             if (Vector3.Distance(transform.position, randomizeCourseVector) < transform.localScale.x)
    64.             {
    65.                 if (goalDoor)
    66.                     randomizedCourse = true;
    67.                 if (goalDoor == null)
    68.                     calculatedNewRandomizeCourseVector = false;
    69.             }
    70.         }
    71.     }
    72.        
    73.     if (playerCell == currentCell)
    74.         transform.position += (playerTransform.position - transform.position).normalized * currentMoveSpeed * Time.deltaTime;
    75. }
    76.  
    77. function OnTriggerEnter (hitTrigger : Collider)
    78. {
    79.     if (hitTrigger.tag == "AIpathCell")
    80.     {
    81.         currentCell = hitTrigger.gameObject;
    82.         randomizedCourse = false;
    83.         calculatedNewRandomizeCourseVector = false;
    84.     }
    85. }
    86.  
    87. function FindRandomSpotInCurrentCell ()
    88. {
    89.     return currentCell.transform.position + (currentCell.transform.rotation * Vector3(Random.Range(currentCell.transform.localScale.x * -0.5,currentCell.transform.localScale.x * 0.5),0,Random.Range(currentCell.transform.localScale.z * -0.5,currentCell.transform.localScale.z * 0.5)));
    90. }
    91.  
    PlayerMovementScript:
    Code (csharp):
    1.  
    2. var currentGun : GameObject;
    3. var distToPickUpGun : float = 6;
    4. var throwGunUpForce : float = 100;
    5. var throwGunForwardForce : float = 300;
    6. var waitFrameForSwitchGuns : int = -1;
    7.  
    8. var walkAcceleration : float = 5;
    9. var walkAccelAirRacio : float = 0.1;
    10. var walkDeacceleration : float = 5;
    11. @HideInInspector
    12. var walkDeaccelerationVolx : float;
    13. @HideInInspector
    14. var walkDeaccelerationVolz : float;
    15.  
    16. var cameraObject : GameObject;
    17. var maxWalkSpeed : float = 20;
    18. @HideInInspector
    19. var horizontalMovement : Vector2;
    20.  
    21. var jumpVelocity : float = 20;
    22. @HideInInspector
    23. var grounded : boolean = false;
    24. var maxSlope : float = 60;
    25.  
    26. var crouchRacio : float = 0.3;
    27. var transitionToCrouchSec : float = 0.2;
    28. var crouchingVelocity : float;
    29. var currentCrouchRacio : float = 1;
    30. var originalLocalScaleY : float;
    31. var crouchLocalScaleY : float;
    32. var collisionDetectionSphere : GameObject;
    33.  
    34. @HideInInspector
    35. var waitToPickupAmmo : float = 0;
    36.  
    37. var currentCell : GameObject;
    38.  
    39. function Awake ()
    40. {
    41.     currentCrouchRacio = 1;
    42.     originalLocalScaleY = transform.localScale.y;
    43.     crouchLocalScaleY = transform.localScale.y * crouchRacio;
    44. }
    45.  
    46. function LateUpdate ()
    47. {
    48.     waitFrameForSwitchGuns -= 1;
    49.     waitToPickupAmmo -= Time.deltaTime;
    50.    
    51.     transform.localScale.y = Mathf.Lerp(crouchLocalScaleY, originalLocalScaleY, currentCrouchRacio);
    52.     if (Input.GetButton("Crouch"))
    53.         currentCrouchRacio = Mathf.SmoothDamp(currentCrouchRacio, 0, crouchingVelocity, transitionToCrouchSec);
    54.     if (Input.GetButton("Crouch") == false  collisionDetectionSphere.GetComponent(CollsionDetectionSphereScript).collisionDetected == false)
    55.         currentCrouchRacio = Mathf.SmoothDamp(currentCrouchRacio, 1, crouchingVelocity, transitionToCrouchSec);
    56.    
    57.     horizontalMovement = Vector2(rigidbody.velocity.x, rigidbody.velocity.z);
    58.     if (horizontalMovement.magnitude > maxWalkSpeed)
    59.     {
    60.         horizontalMovement = horizontalMovement.normalized;
    61.         horizontalMovement *= maxWalkSpeed;    
    62.     }
    63.    
    64.     rigidbody.velocity.x = horizontalMovement.x;
    65.     rigidbody.velocity.z = horizontalMovement.y;
    66.    
    67.     if (grounded){
    68.         rigidbody.velocity.x = Mathf.SmoothDamp(rigidbody.velocity.x, 0, walkDeaccelerationVolx, walkDeacceleration);
    69.         rigidbody.velocity.z = Mathf.SmoothDamp(rigidbody.velocity.z, 0, walkDeaccelerationVolz, walkDeacceleration);}
    70.    
    71.     transform.rotation = Quaternion.Euler(0, cameraObject.GetComponent(MouseLookScript).currentYRotation, 0);
    72.    
    73.     /*if (grounded)
    74.         rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime);
    75.     else
    76.         rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRacio * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * walkAccelAirRacio * Time.deltaTime);
    77.             */
    78.     if (Input.GetButtonDown("Jump")  grounded)
    79.         rigidbody.AddForce(0,jumpVelocity,0);
    80. }
    81.  
    82. function FixedUpdate ()
    83. {
    84.     if (grounded)
    85.         rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration, 0, Input.GetAxis("Vertical") * walkAcceleration);
    86.     else
    87.         rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRacio, 0, Input.GetAxis("Vertical") * walkAcceleration * walkAccelAirRacio);
    88. }
    89.  
    90. function OnCollisionStay (collision : Collision)
    91. {
    92.     for (var contact : ContactPoint in collision.contacts)
    93.     {
    94.         if (Vector3.Angle(contact.normal, Vector3.up) < maxSlope)
    95.             grounded = true;
    96.     }
    97. }
    98.  
    99. function OnCollisionExit ()
    100. {
    101.     grounded = false;
    102. }
    103.  
    104. function OnTriggerExit ()
    105. {
    106.     currentCell = null;
    107. }
    108.  
    109. function OnTriggerStay (hitTrigger : Collider)
    110. {
    111.     if (hitTrigger.tag == "AIpathCell")
    112.         currentCell = hitTrigger.gameObject;
    113.  
    114.     if (hitTrigger.transform.tag == "StairGoingUp")
    115.         if (!Input.GetButton("Jump")  Vector3.Angle(rigidbody.velocity, hitTrigger.transform.forward) < 90)
    116.             if (rigidbody.velocity.y > 0)
    117.                 rigidbody.velocity.y = 0;
    118.     if (hitTrigger.transform.tag == "StairGoingDown")
    119.         if (!Input.GetButton("Jump")  Vector3.Angle(rigidbody.velocity, hitTrigger.transform.forward) < 90)
    120.             rigidbody.AddForce(0,-100,0);
    121.  
    122.  
    123.     var current : GunScript = null;
    124.     if (currentGun)
    125.         current = currentGun.GetComponent(GunScript);
    126.     var ammo : AmmoPickupScript = null;
    127.     var gun : GunScript = null;
    128.     if (hitTrigger.tag == "AmmoPickup"  waitToPickupAmmo <= 0)
    129.     {
    130.         ammo = hitTrigger.gameObject.GetComponent(AmmoPickupScript);
    131.         if (current.currentExtraAmmo < current.maxExtraAmmo)
    132.         {
    133.             if (ammo.fromGun)
    134.             {
    135.                 gun = ammo.gun.GetComponent(GunScript);
    136.                 if (gun.currentExtraAmmo > 0  gun.ammoType == current.ammoType  ammo.gun != currentGun)
    137.                 {
    138.                     if (gun.currentExtraAmmo >= current.maxExtraAmmo - current.currentExtraAmmo)
    139.                     {
    140.                         gun.currentExtraAmmo -= current.maxExtraAmmo - current.currentExtraAmmo;
    141.                         current.currentExtraAmmo = current.maxExtraAmmo;
    142.                     }
    143.                     if (gun.currentExtraAmmo < current.maxExtraAmmo - current.currentExtraAmmo)
    144.                     {
    145.                         current.currentExtraAmmo += gun.currentExtraAmmo;
    146.                         gun.currentExtraAmmo = 0;
    147.                     }
    148.                     if (ammo.pickupSound)
    149.                         ammo.gameObject.GetComponent(AudioSource).Play();
    150.                 }
    151.             }
    152.             if (!ammo.fromGun)
    153.             {
    154.                 if (current.ammoType == ammo.ammoType || ammo.ammoType == -1)
    155.                 {
    156.                     if (ammo.ammoAmount > 0  !ammo.unlimitedAmmo)
    157.                     {
    158.                         if (ammo.ammoAmount >= current.maxExtraAmmo - current.currentExtraAmmo)
    159.                         {
    160.                             ammo.ammoAmount -= current.maxExtraAmmo - current.currentExtraAmmo;
    161.                             current.currentExtraAmmo = current.maxExtraAmmo;
    162.                         }
    163.                         if (ammo.ammoAmount < current.maxExtraAmmo - current.currentExtraAmmo)
    164.                         {
    165.                             current.currentExtraAmmo += gun.currentExtraAmmo;
    166.                             ammo.ammoAmount = 0;
    167.                         }
    168.                         if (ammo.pickupSound)
    169.                             ammo.gameObject.GetComponent(AudioSource).Play();
    170.                     }
    171.                     if (ammo.unlimitedAmmo)
    172.                     {
    173.                         current.currentExtraAmmo = current.maxExtraAmmo;
    174.                         if (ammo.pickupSound)
    175.                             ammo.gameObject.GetComponent(AudioSource).Play();
    176.                     }
    177.                 }
    178.             }
    179.         }
    180.     }
    181. }
    182.  
    AIPathDoorScript:
    Code (csharp):
    1.  
    2. var cells = new Array();
    3. var doorsToCells = new Array();
    4. var imediateCells = new Array();
    5. var testForCells : boolean = true;
    6. var waitToTestCells : float = 2;
    7. var stage : int = 1;
    8.  
    9. var animatedDoor : GameObject;
    10. @HideInInspector
    11. var doorOpen : boolean = true;
    12.  
    13. function Awake ()
    14. {
    15.     doorOpen = true;
    16.     cells = GameObject.FindGameObjectsWithTag("AIpathCell");
    17.     doorsToCells.length = cells.length;
    18.     testForCells = true;
    19.     waitToTestCells = 2;
    20.     stage = 1;
    21. }
    22.  
    23. function Update ()
    24. {
    25.     if (animatedDoor)
    26.         doorOpen = animatedDoor.GetComponent(DoorScript).open;
    27.  
    28.     if (testForCells  waitToTestCells <= 0)
    29.     {
    30.         for (var imediateCell : GameObject in imediateCells)
    31.         {
    32.             for (var i : int = 0; i <= cells.length - 1; i++)
    33.             {
    34.                 if (cells[i] == imediateCell)
    35.                     doorsToCells[i] = 1;
    36.             }
    37.         }
    38.        
    39.         for (stage = 2; stage <= cells.length; stage++)
    40.         {
    41.             for (i = 0; i <= cells.length - 1; i++)
    42.             {
    43.                 if (doorsToCells[i] == stage - 1)
    44.                     for (var checkDoor : GameObject in cells[i].GetComponent(AIpathCellScript).doors)
    45.                     {
    46.                         if (checkDoor != gameObject)
    47.                         {
    48.                             for (var checkCell : GameObject in checkDoor.GetComponent(AIpathDoorScript).imediateCells)
    49.                             {
    50.                                 for (var j : int = 0; j <= cells.length - 1; j++)
    51.                                 {
    52.                                     if (cells[j] == checkCell  doorsToCells[j] == null)
    53.                                         doorsToCells[j] = stage;
    54.                                 }
    55.                             }
    56.                         }
    57.                     }
    58.             }
    59.         }
    60.        
    61.         testForCells = false;
    62.         Debug.Log(doorsToCells);
    63.     }
    64.     waitToTestCells -= 1;
    65. }
    66.  
    67. function OnTriggerEnter (other : Collider)
    68. {
    69.     if (other.tag == "AIpathCell")
    70.         imediateCells.Add(other.gameObject);
    71. }
    72.  
    AIPathCellScript:
    Code (csharp):
    1.  
    2. var doors = new Array();
    3.  
    4. function OnTriggerEnter (other : Collider)
    5. {
    6.     if (other.tag == "AIpathDoor")
    7.         doors.Add(other.gameObject);
    8. }
    9.  
    DoorScript:
    Code (csharp):
    1.  
    2. var open : boolean = false;
    3.  
    4. var openAnimationString : String;
    5. var closeAnimationString : String;
    6.  
    7. var buttonTransform : Transform;
    8. var distToOpen : float = 4;
    9.  
    10. @HideInInspector
    11. var playerTransform : Transform;
    12. @HideInInspector
    13. var cameraTransform : Transform;
    14.  
    15. var openSound : AudioClip;
    16. var closeSound : AudioClip;
    17.  
    18. function Awake ()
    19. {
    20.     playerTransform = GameObject.FindWithTag("Player").transform;
    21.     cameraTransform = GameObject.FindWithTag("MainCamera").transform;
    22.     if (open)
    23.         animation.Play(openAnimationString);
    24. }
    25.  
    26. function Update ()
    27. {
    28.     var alreadyChecked : boolean = false;
    29.     var angle : float = Vector3.Angle(buttonTransform.position - cameraTransform.position, buttonTransform.position + (cameraTransform.right * buttonTransform.localScale.magnitude) - cameraTransform.position);
    30.     if (Vector3.Distance(playerTransform.position,buttonTransform.position) <= distToOpen)
    31.     if (Vector3.Angle(buttonTransform.position - cameraTransform.position, cameraTransform.forward) <= angle)
    32.     if (Input.GetButtonDown("Use Key")  !animation.isPlaying)
    33.     {
    34.         if (open)
    35.         {
    36.             animation.Play(closeAnimationString);
    37.             open = false;
    38.             alreadyChecked = true;
    39.             if (closeSound)
    40.                 audio.PlayOneShot(closeSound);
    41.         }
    42.         if (!open  !alreadyChecked)
    43.         {
    44.             animation.Play(openAnimationString);
    45.             open = true;
    46.             if (openSound)
    47.                 audio.PlayOneShot(openSound);
    48.         }
    49.     }
    50. }
    51.  
     
    Last edited: Jun 8, 2012
  2. ivan12948

    ivan12948

    Joined:
    Aug 22, 2012
    Posts:
    1
    how can i implement this on mobile flatform?
    im getting this error: 'GetComponent' is not a member of 'Object'. on

    for (var doorCheckingNow : GameObject in currentCell.GetComponent(AIpathCellScript).doors)
     
    AlphaGarg8447 likes this.
  3. AlphaGarg8447

    AlphaGarg8447

    Joined:
    Jul 28, 2013
    Posts:
    20
    What about putting up a link? Im getting parsing errors and a bunch of unexpected symbols (+, :, =, etc)