Search Unity

How to create Enemy Ai

Discussion in 'Game Design' started by vickymotasara, Oct 12, 2020.

  1. vickymotasara

    vickymotasara

    Joined:
    Jun 2, 2020
    Posts:
    6
    Currently I am Working On Game Based on A movie, In which player is stuck inside a maze and he has to find keys to unlock doors and solve sum puzzles and gt out of maze also he is followed my zombies. Every thing is ready accept Enemy. I want to Create An Enemy That moves Randomly in side the Maze , if Enemy Sees Player then it moves towards player and attack him or if Enemy Hears a gun Shot then it should Trace the aprrox. position of gun shot.


    This is My Enemy Script

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityStandardAssets.Characters.ThirdPerson;
    5. using UnityEngine.AI;
    6.  
    7. public class ScanForPlayer : MonoBehaviour
    8. {
    9.     public float viewDistance;
    10.     public float viewAngle;
    11.     public LayerMask viewMask;
    12.  
    13.     Transform player;
    14.  
    15.     bool playerIsVisible;
    16.  
    17.     public NavMeshAgent agent;
    18.  
    19.     public ThirdPersonCharacter character;
    20.  
    21.     void Start()
    22.     {
    23.         player = GameObject.FindWithTag("Player").transform;
    24.         agent.updateRotation = false;
    25.     }
    26.  
    27.     void Update()
    28.     {
    29.         playerIsVisible = CanSeePlayer ();
    30.  
    31.         if (agent.remainingDistance <= 1f || playerIsVisible || (Vector3.Distance (transform.position, FindObjectOfType<Shooting> ().FirePos) < viewDistance / 2 && FindObjectOfType<Shooting> ().isShooting)) {
    32.             AgentMover ();
    33.         }
    34.  
    35.         character.Move (agent.desiredVelocity, false, false);
    36.     }
    37.  
    38.     bool CanSeePlayer()
    39.     {
    40.         if (Vector3.Distance(transform.position, player.position) < viewDistance)
    41.         {
    42.             Vector3 dirToPlayer = (player.position - transform.position).normalized;
    43.             float angleBetweenGuardAndPlayer = Vector3.Angle(transform.forward, dirToPlayer);
    44.             if (angleBetweenGuardAndPlayer < viewAngle / 2f)
    45.             {
    46.                 if (!Physics.Linecast(transform.position, player.position, viewMask))
    47.                 {
    48.                     return true;
    49.                 }
    50.             }
    51.         }
    52.         return false;
    53.     }
    54.     Vector3 RandomNavSphere (Vector3 origin, float dist, int layermask)
    55.     {
    56.         Vector3 randDirection = Random.insideUnitSphere * dist;
    57.         randDirection += origin;
    58.         UnityEngine.AI.NavMeshHit navHit;
    59.         UnityEngine.AI.NavMesh.SamplePosition (randDirection, out navHit, dist, layermask);
    60.  
    61.         if (Vector3.Distance (transform.position, FindObjectOfType<Shooting>().FirePos) < viewDistance/2 && FindObjectOfType<Shooting>().isShooting) {
    62.             return FindObjectOfType<Shooting> ().FirePos;
    63.         }
    64.  
    65.         return navHit.position;
    66.     }
    67.  
    68.     void AgentMover ()
    69.     {
    70.         if (agent.remainingDistance <= 1f || playerIsVisible || (Vector3.Distance (transform.position, FindObjectOfType<Shooting> ().FirePos) < viewDistance / 2 && FindObjectOfType<Shooting> ().isShooting) || agent.isStoppeds) {
    71.            
    72.        
    73.             if (Vector3.Distance (transform.position, player.position) > 1) {
    74.                 if (playerIsVisible) {
    75.                     agent.SetDestination (player.position);
    76.                 } else {
    77.                     agent.SetDestination (RandomNavSphere (transform.position, viewDistance * 10, viewMask));
    78.                 }
    79.             } else {
    80.                 agent.isStopped = true;
    81.                 Debug.Log ("Daed");
    82.             }
    83.         }
    84.     }
    85. }
    here my player script

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityStandardAssets.Characters.ThirdPerson;
    5. using UnityEngine.AI;
    6.  
    7. public class ScanForPlayer : MonoBehaviour
    8. {
    9.     public float viewDistance;
    10.     public float viewAngle;
    11.     public LayerMask viewMask;
    12.  
    13.     Transform player;
    14.  
    15.     bool playerIsVisible;
    16.  
    17.     public NavMeshAgent agent;
    18.  
    19.     public ThirdPersonCharacter character;
    20.  
    21.     void Start()
    22.     {
    23.         player = GameObject.FindWithTag("Player").transform;
    24.         agent.updateRotation = false;
    25.     }
    26.  
    27.     void Update()
    28.     {
    29.         playerIsVisible = CanSeePlayer ();
    30.  
    31.         if (agent.remainingDistance <= 1f || playerIsVisible || (Vector3.Distance (transform.position, FindObjectOfType<Shooting> ().FirePos) < viewDistance / 2 && FindObjectOfType<Shooting> ().isShooting)) {
    32.             AgentMover ();
    33.         }
    34.  
    35.         character.Move (agent.desiredVelocity, false, false);
    36.     }
    37.  
    38.     bool CanSeePlayer()
    39.     {
    40.         if (Vector3.Distance(transform.position, player.position) < viewDistance)
    41.         {
    42.             Vector3 dirToPlayer = (player.position - transform.position).normalized;
    43.             float angleBetweenGuardAndPlayer = Vector3.Angle(transform.forward, dirToPlayer);
    44.             if (angleBetweenGuardAndPlayer < viewAngle / 2f)
    45.             {
    46.                 if (!Physics.Linecast(transform.position, player.position, viewMask))
    47.                 {
    48.                     return true;
    49.                 }
    50.             }
    51.         }
    52.         return false;
    53.     }
    54.     Vector3 RandomNavSphere (Vector3 origin, float dist, int layermask)
    55.     {
    56.         Vector3 randDirection = Random.insideUnitSphere * dist;
    57.         randDirection += origin;
    58.         UnityEngine.AI.NavMeshHit navHit;
    59.         UnityEngine.AI.NavMesh.SamplePosition (randDirection, out navHit, dist, layermask);
    60.  
    61.         if (Vector3.Distance (transform.position, FindObjectOfType<Shooting>().FirePos) < viewDistance/2 && FindObjectOfType<Shooting>().isShooting) {
    62.             return FindObjectOfType<Shooting> ().FirePos;
    63.         }
    64.  
    65.         return navHit.position;
    66.     }
    67.  
    68.     void AgentMover ()
    69.     {
    70.         if (agent.remainingDistance <= 1f || playerIsVisible || (Vector3.Distance (transform.position, FindObjectOfType<Shooting> ().FirePos) < viewDistance / 2 && FindObjectOfType<Shooting> ().isShooting) || agent.isStoppeds) {
    71.            
    72.        
    73.             if (Vector3.Distance (transform.position, player.position) > 1) {
    74.                 if (playerIsVisible) {
    75.                     agent.SetDestination (player.position);
    76.                 } else {
    77.                     agent.SetDestination (RandomNavSphere (transform.position, viewDistance * 10, viewMask));
    78.                 }
    79.             } else {
    80.                 agent.isStopped = true;
    81.                 Debug.Log ("Dead");
    82.             }
    83.         }
    84.     }
    85. }
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Sounds like a good plan!

    Are you having any trouble with it?
     
    BrandyStarbrite and Vryken like this.
  3. vickymotasara

    vickymotasara

    Joined:
    Jun 2, 2020
    Posts:
    6

    yaaa, As enemy ai Doesn't seems to work properly, when it is near to player, it behaves strangely, it either completely stops(means if we move away from enemy it doesn't chase player anymore) or calculate new path(even if we don't move from place enemy would calculate new path and moves away).
     
  4. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Well, your AgentMover() method has a very long if statement with a whole bunch of conditions I don't have time today to figure out. But my guess is, that's probably where things are going wrong.

    Try breaking that up a bit, or introducing some local variables that capture what those conditions actually mean to you. And use Debug.Log to ensure that they are functioning correctly.
     
    Not_Sure likes this.
  5. Not_Sure

    Not_Sure

    Joined:
    Dec 13, 2011
    Posts:
    3,546
    This.

    I like to put “bing” “bang” “boom” at every stage of the chain of events to find out which one is failing.

    Im sure you could use numbers, but where’s the fun in that?
     
    BrandyStarbrite likes this.
  6. vickymotasara

    vickymotasara

    Joined:
    Jun 2, 2020
    Posts:
    6
    Code (CSharp):
    1. if (Vector3.Distance (transform.position, player.position) > 1) {
    2.                 if (playerIsVisible) {
    3.                     agent.SetDestination (player.position);
    4.                 } else {
    5.                     agent.SetDestination (RandomNavSphere (transform.position, viewDistance * 10, viewMask));
    6.                 }
    7.             } else {
    8.                 agent.isStopped = true;
    9.                 Debug.Log ("Daed");
    10.             }
    Problem is with this....

    Agent is either completely stops or keeps moving when he approaches the player
     
  7. vickymotasara

    vickymotasara

    Joined:
    Jun 2, 2020
    Posts:
    6
    By the way, I have solved the problem....

    But....

    Now I encountered another....

    Playing different animation.
    Any idea how to use animator with my enemy script
     
  8. vickymotasara

    vickymotasara

    Joined:
    Jun 2, 2020
    Posts:
    6
    Your trick seems to work :)
     
    Not_Sure likes this.
  9. BrandyStarbrite

    BrandyStarbrite

    Joined:
    Aug 4, 2013
    Posts:
    2,076
    Aye, good idea.
     
  10. F1v3s4nd3ch0

    F1v3s4nd3ch0

    Joined:
    Dec 11, 2021
    Posts:
    1
    Hey vickymotasara, what is 'ThirdPersonCharacter'? Is this a name?
     
  11. YBtheS

    YBtheS

    Joined:
    Feb 22, 2016
    Posts:
    239
    It is a class within the
    UnityStandardAssets.Characters.ThirdPerson
    namespace.