SHARE
TWEET

CreepScript

a guest May 17th, 2017 222 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /// <summary>
  2. /// AI character controller.
  3. /// Just A basic AI Character controller
  4. /// will looking for a Target and moving to and Attacking
  5. /// </summary>
  6.  
  7. using UnityEngine;
  8. using System.Collections;
  9. using System.Collections.Generic;
  10.  
  11. [RequireComponent(typeof (Animator))]
  12. [RequireComponent(typeof(CharacterController))]
  13. [RequireComponent(typeof (UnityEngine.AI.NavMeshAgent))]
  14. [RequireComponent(typeof (AudioSource))]
  15. [RequireComponent(typeof (PlayerStats))]
  16.  
  17. public class CreepScript : uLink.MonoBehaviour {
  18.     //UPDATE RATE OF THE AGENT.SETDESTINATION
  19.     private float updateTargetRate = 10F;
  20.  
  21.     //VARIABLE USED TO STORE THE CURRENT TARGET OBJ
  22.     private GameObject targetObj;
  23.  
  24.     //USED TO STORE THE TRIGGER GAMEOBJ
  25.     public Transform trigger;
  26.  
  27.     //OBJ TO DROP WHEN THIS CREEP DIE
  28.     public GameObject dropObj;
  29.  
  30.     //STATE OF THE CREEP
  31.     public enum State
  32.     {
  33.         idle,
  34.        
  35.         chasing,
  36.        
  37.         attackingMelee,
  38.        
  39.         attackingRangue,
  40.  
  41.         retreat,
  42.  
  43.         dead
  44.        
  45.        
  46.     }
  47.     //CURRENT STATE OF THE CREEP
  48.     public State creepStatus = State.idle;
  49.  
  50.     //ATTACK SPEED RATE
  51.     public float attackSpeed = 3;
  52.     private float timeAttack = 0;
  53.  
  54.     //COMPONETS VARIABLE
  55.     private Animator animator;
  56.  
  57.     //DISTANCE FROM THE ENEMY AND MAXIMUN DISTANCE ALLOWED
  58.     private float distanceFromPlayer;
  59.     public float attackRange = 2;
  60.     public float maxDistance = 6;
  61.  
  62.     //PLAYERSTATS SCRIPT THAT STORES ALL THE STATS ABOUT THIS OBJ
  63.     private PlayerStats playerStatsScript;
  64.  
  65.     //CALCULATE POSITION AND ROTATIONS
  66.     private float distanceFromOrigin;
  67.     private Quaternion initialRotation;
  68.     private Vector3 objectPos;
  69.     private Vector3 initialPos;
  70.  
  71.  
  72.     //AUDIO CLIPS
  73.     private AudioSource audioSource;
  74.     public AudioClip attackingSound;
  75.     public AudioClip chasingSound;
  76.     public AudioClip talkingSound;
  77.  
  78.     //agent variables
  79.     public UnityEngine.AI.NavMeshAgent agent { get; private set; } // the navmesh agent required for the path finding
  80.     private Vector3 move;
  81.     private float m_MovingTurnSpeed = 360;
  82.     private float m_StationaryTurnSpeed = 1000;
  83.     float m_TurnAmount;
  84.     float m_ForwardAmount;
  85.  
  86.     //VARIABLES USED TO STORE THE ENEMY PATH AND THE PATH TO THE INITIAL POSITION
  87.     private UnityEngine.AI.NavMeshPath enemyPosPath;
  88.     private UnityEngine.AI.NavMeshPath initPosPath;
  89.    
  90.     void Start () {
  91.  
  92.    
  93.         animator = GetComponent<Animator>();
  94.         audioSource = GetComponent<AudioSource>();
  95.         playerStatsScript = GetComponent<PlayerStats>();
  96.         agent = GetComponentInChildren<UnityEngine.AI.NavMeshAgent>();
  97.         if (gameObject.transform.FindChild("Trigger"))
  98.         {
  99.             trigger = gameObject.transform.FindChild("Trigger");
  100.         }
  101.         else
  102.         {
  103.             Debug.Log("ERROR : There is no gameobject called Trigger on the child hierarchy");
  104.         }
  105.  
  106.         agent.updateRotation = false;
  107.         agent.updatePosition = true;
  108.         initialPos = transform.position;
  109.         initialRotation = transform.rotation;
  110.         enemyPosPath = new UnityEngine.AI.NavMeshPath();
  111.         initPosPath = new UnityEngine.AI.NavMeshPath();
  112.  
  113.         Debug.Log(playerStatsScript.stats.charPortrait);
  114.     }
  115.    
  116.  
  117.     void PlayTalkSound()
  118.     {
  119.         if (creepStatus == State.idle)
  120.         audioSource.PlayOneShot(talkingSound, 0.7f);
  121.  
  122.         Invoke("PlayTalkSound", Random.Range(5, 20));
  123.     }
  124.     void OnTriggerEnter(Collider other)
  125.     {
  126.         if (playerStatsScript.PlayerTeam == "boss")
  127.         {
  128.             if(other.tag == "RedPlayerTag" || other.tag == "BluePlayerTag")
  129.             {          
  130.                 networkView.RPC("PlayClientSound", uLink.RPCMode.Others, 1);
  131.                 targetObj = other.gameObject;
  132.             }
  133.         }
  134.         if (playerStatsScript.PlayerTeam == "blue")
  135.         {
  136.             if(other.tag == "RedPlayerTag")
  137.             {          
  138.  
  139.                 targetObj = other.gameObject;
  140.  
  141.             }
  142.         }
  143.         if (playerStatsScript.PlayerTeam == "red")
  144.         {
  145.             if(other.tag == "BluePlayerTag")
  146.             {          
  147.  
  148.                 targetObj = other.gameObject;
  149.             }
  150.         }
  151.  
  152.    
  153.     }
  154.  
  155.  
  156.     private float PathLength(UnityEngine.AI.NavMeshPath path) {
  157.         // The length is implicitly zero if there aren't at least
  158.         // two corners in the path.
  159.         if (path.corners.Length < 2)
  160.             return 0;
  161.        
  162.         var previousCorner = path.corners[0];
  163.         float lengthSoFar = 0;
  164.        
  165.         // Calculate the total distance by adding up the lengths
  166.         // of the straight lines between corners.
  167.         for (var i = 1; i < path.corners.Length; i++) {
  168.             var currentCorner = path.corners[i];
  169.             lengthSoFar += Vector3.Distance(previousCorner, currentCorner);
  170.             previousCorner = currentCorner;
  171.         }
  172.        
  173.         return lengthSoFar;
  174.     }
  175.  
  176.    
  177.     void Update ()
  178.     {
  179.  
  180.         //If the game has ended do nothing!
  181.         if (ScoreTable.instance.GameEnded == true)
  182.         {
  183.             animator.Stop;
  184.             return;
  185.         }
  186.        
  187.        
  188.         if (uLink.Network.isClient)
  189.         {
  190.             GetComponent<SphereCollider>().enabled = false;
  191.         }
  192.  
  193.         if (playerStatsScript.abilityLocked && playerStatsScript.Health > 0)
  194.         {
  195.             if (uLink.Network.isServer)
  196.             {
  197.                 agent.Stop();
  198.                 creepStatus = State.idle;
  199.             }
  200.             animator.enabled = false;
  201.             return;
  202.         }
  203.         else
  204.         {
  205.             animator.enabled = true;
  206.         }
  207.  
  208.  
  209.         if (uLink.Network.isServer)
  210.         {
  211.            
  212.  
  213.        
  214.             //CALCULATE ATTACKING TIME
  215.             timeAttack += Time.deltaTime;
  216.            
  217.             var direction = Vector3.zero;
  218.             var myPos = this.gameObject.transform.position;
  219.        
  220.  
  221.            
  222.             if(targetObj)
  223.                
  224.             {
  225.  
  226.                 objectPos = targetObj.transform.position;
  227.                 objectPos.y = myPos.y;
  228.                 agent.CalculatePath(objectPos, enemyPosPath);
  229.                 distanceFromPlayer = PathLength(enemyPosPath);
  230.  
  231.  
  232.                
  233.  
  234.                 if (distanceFromPlayer > maxDistance +2)
  235.                     targetObj = null;
  236.             }
  237.  
  238.             //Case for all the states of the creep enemy
  239.             //This is used to control the animations and attacks
  240.             switch (creepStatus)
  241.             {
  242.             case State.idle:
  243.  
  244.                 if (playerStatsScript.Health < playerStatsScript.HealthMax && Vector3.Distance(transform.position, initialPos) < 0.2);
  245.                 {
  246.                     //playerStatsScript.Health = playerStatsScript.HealthMax;
  247.                     playerStatsScript.UpdateHealthClients();
  248.                 }
  249.                 if (uLink.Network.isServer)
  250.                 agent.Stop();
  251.                 //If a player is detected in this range, the enemy will start chasing
  252.                 if(distanceFromPlayer<=maxDistance - 2 && targetObj) {
  253.                 creepStatus = State.attackingMelee;
  254.                 }
  255.  
  256.                 transform.rotation = initialRotation;
  257.                 animator.SetInteger("AnimType", (int)State.idle);
  258.  
  259.                 break;
  260.             case State.dead:
  261.  
  262.                 agent.Stop();
  263.                 animator.SetInteger("AnimType", (int)State.dead);
  264.            
  265.                 break;
  266.             case State.attackingMelee:
  267.  
  268.                 if (!targetObj)
  269.                 {
  270.                     creepStatus = State.retreat;
  271.                     return;
  272.                 }
  273.                 else
  274.                 {
  275.                     PlayerStats enemyPlayerStatsScript = targetObj.GetComponent<PlayerStats>();
  276.                     if (enemyPlayerStatsScript.Health <=0)
  277.                     {
  278.                         creepStatus = State.retreat;
  279.                         return;
  280.                     }
  281.                     transform.LookAt(targetObj.transform.position);
  282.                 }
  283.  
  284.                 if (!playerStatsScript.charLocked)
  285.                 {
  286.  
  287.  
  288.  
  289.                     if(distanceFromPlayer<=attackRange) {
  290.                         if (timeAttack > attackSpeed)
  291.                         {
  292.  
  293.                             audioSource.PlayOneShot(attackingSound, 0.7f);
  294.                             agent.Stop();
  295.                             animator.SetInteger("AnimType", (int)State.attackingMelee);
  296.                             playerStatsScript.charLocked = true;
  297.                             timeAttack = 0;
  298.                         }
  299.                         else
  300.                         {
  301.                             agent.Stop();
  302.                             animator.SetInteger("AnimType", (int)State.idle);
  303.                         }
  304.                     }
  305.                     else
  306.                     {
  307.                         animator.SetInteger("AnimType", (int)State.chasing);
  308.  
  309.                        
  310.                         MoveOrChase();
  311.                     }
  312.  
  313.                     agent.CalculatePath(initialPos, initPosPath);
  314.                     distanceFromOrigin = PathLength(initPosPath);
  315.  
  316.                     if (distanceFromOrigin > maxDistance)
  317.  
  318.                    
  319.                    
  320.  
  321.                         if(distanceFromPlayer>=maxDistance || distanceFromOrigin > maxDistance)
  322.                         {  
  323.                            
  324.                             targetObj = null;
  325.                             agent.SetDestination(initialPos);
  326.                             creepStatus = State.retreat;
  327.  
  328.                         }
  329.                 }
  330.                 break;
  331.             }
  332.  
  333.  
  334.  
  335.             if (creepStatus == State.retreat)
  336.             {
  337.                 agent.CalculatePath(initialPos, initPosPath);
  338.                 distanceFromOrigin = PathLength(initPosPath);
  339.  
  340.                 if (distanceFromOrigin > 0.5f)
  341.                 {
  342.                     targetObj = null;
  343.                
  344.                     animator.SetInteger("AnimType", (int)State.chasing);
  345.  
  346.                     direction = this.transform.forward;
  347.                     direction.Normalize();
  348.  
  349.  
  350.                     MoveOrChase();
  351.                 }
  352.                 else
  353.                 {
  354.                     //playerStatsScript.Health = playerStatsScript.HealthMax;
  355.                     playerStatsScript.UpdateHealthClients();
  356.                     creepStatus = State.idle;
  357.                 }
  358.             }
  359.  
  360.  
  361.  
  362.  
  363.  
  364.  
  365.         }
  366.         else if (uLink.Network.isClient)
  367.         {
  368.             agent.enabled = false;
  369.         }
  370.  
  371.  
  372.     }
  373.  
  374.     void MoveOrChase()
  375.     {
  376.             agent.Resume();
  377.  
  378.             updateTargetRate++;
  379.             if (updateTargetRate > 5)
  380.             {
  381.                 if (targetObj != null)
  382.                 {
  383.                     updateTargetRate = 0;
  384.                     agent.SetDestination(targetObj.transform.position);
  385.                 }
  386.                 else
  387.                 {
  388.                     updateTargetRate = 0;
  389.                     agent.SetDestination(initialPos);
  390.                 }
  391.             }
  392.  
  393.    
  394.        
  395.        
  396.         move = agent.desiredVelocity;
  397.         if (move.magnitude > 1f) move.Normalize();
  398.         move = transform.InverseTransformDirection(move);
  399.         move = Vector3.ProjectOnPlane(move, Vector3.zero);
  400.         m_TurnAmount = Mathf.Atan2(move.x, move.z);
  401.         m_ForwardAmount = move.z;
  402.    
  403.         float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
  404.         transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
  405.         transform.LookAt(agent.nextPosition);
  406.  
  407.        
  408.     }
  409.     //Called on animation events to unlock the character when the animation ends
  410.     void ExitAnim()
  411.     {
  412.         playerStatsScript.charLocked = false;
  413.        
  414.     }
  415.  
  416.     void Attacking(State type) {
  417.         audioSource.PlayOneShot(attackingSound, 0.7f);
  418.         if (!uLink.Network.isServer)
  419.             return;
  420.    
  421.  
  422.         switch (type)
  423.         {
  424.         case State.attackingMelee:
  425.  
  426.             animator.SetInteger("AnimType", 0);
  427.             playerStatsScript.charLocked = false;
  428.             break;
  429.         }
  430.  
  431.    
  432.         PlayerStats enemyPlayerStatsScript = targetObj.GetComponent<PlayerStats>();
  433.         enemyPlayerStatsScript.DrainHealth(playerStatsScript.BAdValue, playerStatsScript.BApValue, transform.name, this.gameObject, this.gameObject.tag, CharacterClass.charName.Empty);
  434.  
  435.     }
  436.  
  437.     //This respawn the character on the server
  438.     [RPC]
  439.     public void Respawn ()
  440.     {
  441.  
  442.         if (uLink.Network.isServer)
  443.         {
  444.             //playerStatsScript.HealthMax *= 2;
  445.             //playerStatsScript._bAdValue *= 2;
  446.             //playerStatsScript._bApValue *= 2;
  447.             //playerStatsScript.adRes *= 1.5f;
  448.             //playerStatsScript.apRes *= 1.5f;
  449.             //playerStatsScript.Health = playerStatsScript.HealthMax;
  450.             playerStatsScript.playerLvl++;
  451.             playerStatsScript.destroyed = false;
  452.             //playerStatsScript.UpdateDataOnClients();
  453.        
  454.         }
  455.        
  456.     }
  457.  
  458.     [RPC]
  459.     public void PlayClientSound (int type)
  460.     {
  461.         if (type == 1)
  462.             audioSource.PlayOneShot(chasingSound, 0.7f);
  463.  
  464.     }
  465.  
  466.     [RPC]
  467.     public IEnumerator ImDead()
  468.     {
  469.         if (uLink.Network.isServer && dropObj)
  470.         {
  471.             Vector3 dropPos = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
  472.             uLink.Network.Instantiate(uLink.NetworkPlayer.server, dropObj,dropObj,dropObj, dropPos, Quaternion.identity, 0);
  473.  
  474.         }
  475.         creepStatus = State.dead;
  476.         trigger.GetComponent<BoxCollider>().enabled = false;
  477.         animator.SetInteger("AnimType", (int)State.dead);
  478.         yield return new WaitForSeconds(playerStatsScript.RespawnTime);
  479.         targetObj = null;
  480.         trigger.GetComponent<BoxCollider>().enabled = true;
  481.         creepStatus = State.idle;
  482.         animator.SetInteger("AnimType", (int)State.idle);
  483.         if (uLink.Network.isServer)
  484.         {
  485.             agent.Warp(initialPos);
  486.             agent.ResetPath();
  487.             transform.rotation = initialRotation;
  488.             Respawn();
  489.         }
  490.  
  491.        
  492.        
  493.        
  494.     }
  495.  
  496.  
  497. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top