Search Unity

Question help pls

Discussion in 'Navigation' started by OddByte, May 13, 2023.

  1. OddByte

    OddByte

    Joined:
    Mar 5, 2022
    Posts:
    4
    im trying to make a AI agent that can hear stuff, but the ai just wont hear anything. heres my code. please help.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.AI;
    3.  
    4. public class EnemyAI : MonoBehaviour
    5. {
    6.     public NavMeshAgent agent;
    7.  
    8.     public Transform player;
    9.  
    10.     public LayerMask whatIsGround, whatIsPlayer;
    11.  
    12.     //Patroling
    13.     public Vector3 walkPoint;
    14.     bool walkPointSet;
    15.     public float walkPointRange;
    16.  
    17.     //Attacking
    18.     public float timeBetweenAttacks;
    19.     bool alreadyAttacked;
    20.     public GameObject projectile;
    21.  
    22.     //States
    23.     public float sightRange, attackRange;
    24.     public float fieldOfViewAngle = 160f;
    25.     public bool playerInSightRange, playerInAttackRange;
    26.     public bool isDisabled = false;
    27.  
    28.     //Sound detection
    29.     public float hearingRange = 200f;
    30.     public float hearingThreshold = 2.5f;
    31.  
    32.     public void ToggleAi(){
    33.         isDisabled = !isDisabled;
    34.     }
    35.  
    36.     private void Awake()
    37.     {
    38.         player = GameObject.Find("PlayerObj").transform;
    39.         agent = GetComponent<NavMeshAgent>();
    40.     }
    41.  
    42.  
    43. private void Update()
    44. {
    45.     if (isDisabled)
    46.     {
    47.         agent.SetDestination(gameObject.transform.position);
    48.         return;
    49.     }
    50.     // Check for sight and attack range
    51.     playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer)
    52.         && CanSeePlayer() && !IsPlayerObstructed();
    53.  
    54.     playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer)
    55.         && CanSeePlayer() && !IsPlayerObstructed();
    56.  
    57.             if (CanSeePlayer())
    58.     {
    59.         // Player is visible, use their real position
    60.         lastKnownPlayerPosition = player.position;
    61.         hasseenplayeryet = true;
    62.     }
    63.  
    64.     // Get off ramp if necessary
    65.     if (IsOnRamp())
    66.     {
    67.         GetOffRamp();
    68.         return;
    69.     }
    70.  
    71.     // Check for sound within hearing range and investigate if necessary
    72. // Check for sound within hearing range and investigate if necessary
    73. Collider[] colliders = Physics.OverlapSphere(transform.position, hearingRange);
    74. foreach (Collider collider in colliders)
    75. {
    76.     AudioSource audioSource = collider.GetComponent<AudioSource>();
    77.     if (audioSource != null && audioSource.isPlaying)
    78.     {
    79.         float distance = Vector3.Distance(transform.position, collider.transform.position);
    80.         if (distance <= hearingThreshold)
    81.         {
    82.             // Investigate the sound
    83.             Vector3 soundDirection = audioSource.transform.position - transform.position;
    84.             walkPoint = audioSource.transform.position;
    85.             walkPointSet = true;
    86.         }
    87.     }
    88. }
    89.  
    90.  
    91.  
    92.     if (!playerInSightRange && !playerInAttackRange)
    93.     {
    94.         Patroling();
    95.     }
    96.  
    97.     if (playerInSightRange && !playerInAttackRange)
    98.     {
    99.         ChasePlayer();
    100.     }
    101.  
    102.     if (playerInAttackRange && playerInSightRange)
    103.     {
    104.         AttackPlayer();
    105.     }
    106. }
    107.  
    108. private bool IsOnRamp()
    109. {
    110.     RaycastHit hit;
    111.     if (Physics.Raycast(transform.position, -transform.up, out hit, 2f, whatIsGround))
    112.     {
    113.         return hit.collider.CompareTag("Ramp");
    114.     }
    115.  
    116.     return false;
    117. }
    118. Vector3 lastKnownPlayerPosition;
    119. private void GetOffRamp()
    120. {
    121.     // Determine which way to go based on player's position
    122.     Vector3 playerDirection = player.position - transform.position;
    123.     Vector3 rampNormal = transform.up;
    124.     Vector3 perpendicular = Vector3.Cross(playerDirection, rampNormal);
    125.  
    126.     // Check if player is visible
    127.     if (CanSeePlayer())
    128.     {
    129.         // Player is visible, use their real position
    130.         lastKnownPlayerPosition = player.position;
    131.         agent.SetDestination(lastKnownPlayerPosition  * walkPointRange);
    132.     }
    133.     else if (hasseenplayeryet)
    134.     {
    135.         // Player is not visible but we have a last known position, use that
    136.         agent.SetDestination((Vector3) lastKnownPlayerPosition);
    137.     }
    138.     else
    139.     {
    140.         // Player is not visible and we don't have a last known position, use walk point
    141.         agent.SetDestination(walkPoint);
    142.     }
    143. }
    144.  
    145.  
    146.  
    147.  
    148. private bool CanSeePlayer()
    149. {
    150.     Vector3 direction = player.position - transform.position;
    151.     float angle = Vector3.Angle(direction, transform.forward);
    152.  
    153.     if (angle < fieldOfViewAngle * 0.5f)
    154.     {
    155.         RaycastHit hit3;
    156.         if (Physics.Raycast(transform.position, direction.normalized, out hit3, sightRange))
    157.         {
    158.             if (hit3.collider.CompareTag("Player"))
    159.             {
    160.                 return true;
    161.             }
    162.         }
    163.     }
    164.  
    165.     return false;
    166. }
    167.  
    168. private bool IsPlayerObstructed()
    169. {
    170.     RaycastHit hit2;
    171.     if (Physics.Raycast(transform.position, player.position - transform.position, out hit2, sightRange))
    172.     {
    173.         if (!(hit2.collider.gameObject.layer == LayerMask.NameToLayer("Player")))
    174.         {
    175.             return true;
    176.         }
    177.     }
    178.  
    179.     if (Physics.Raycast(transform.position, player.position - transform.position, out hit2, attackRange))
    180.     {
    181.         if (!(hit2.collider.gameObject.layer == LayerMask.NameToLayer("Player")))
    182.         {
    183.             return true;
    184.         }
    185.     }
    186.  
    187.     return false;
    188. }
    189.  
    190.     private void Patroling()
    191.     {
    192.         if (isDisabled){
    193.             agent.SetDestination(gameObject.transform.position);
    194.             return;
    195.         }
    196.         if (!walkPointSet) SearchWalkPoint();
    197.  
    198.         if (walkPointSet)
    199.             agent.SetDestination(walkPoint);
    200.  
    201.         Vector3 distanceToWalkPoint = transform.position - walkPoint;
    202.  
    203.         //Walkpoint reached
    204.         if (distanceToWalkPoint.magnitude < 1f)
    205.             walkPointSet = false;
    206.     }
    207.     private void SearchWalkPoint()
    208.     {
    209.        
    210.         if (isDisabled){
    211.             agent.SetDestination(gameObject.transform.position);
    212.             return;
    213.         }
    214.         //Calculate random point in range
    215.         float randomZ = Random.Range(-walkPointRange, walkPointRange);
    216.         float randomX = Random.Range(-walkPointRange, walkPointRange);
    217.  
    218.         walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
    219.  
    220.         if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround))
    221.             walkPointSet = true;
    222.     }
    223. private bool hasseenplayeryet;
    224. private bool obstacleInWay;
    225. public void UpdateLocation(){
    226.    
    227.         if (isDisabled){
    228.             agent.SetDestination(gameObject.transform.position);
    229.             return;
    230.         }
    231.     walkPoint = lastKnownPlayerPosition;
    232.     agent.SetDestination(walkPoint);
    233. }
    234.     private void ChasePlayer()
    235.     {
    236.        
    237.        
    238.         if (isDisabled){
    239.             agent.SetDestination(gameObject.transform.position);
    240.             return;
    241.         }
    242.         Vector3 direction = player.position - transform.position;
    243.         float angle = Vector3.Angle(direction, transform.forward);
    244.         // Check if there are any obstacles between the enemy and the player
    245. if (!Physics.Linecast(transform.position, player.position, out RaycastHit hit, ~whatIsPlayer))
    246. {
    247.     if (hit.collider.CompareTag("Player"))
    248.     {
    249.         // Player is visible, no obstacles in the way
    250.         obstacleInWay = false;
    251.     }
    252.     else
    253.     {
    254.         // Something else is blocking the enemy's view of the player
    255.         obstacleInWay = true;
    256.     }
    257. }
    258. else
    259. {
    260.     // Nothing is blocking the enemy's view of the player
    261.     obstacleInWay = false;
    262. }
    263.  
    264.  
    265.         if (angle < fieldOfViewAngle * 0.5f)
    266.         {
    267.             RaycastHit hit1;
    268.             if (Physics.Raycast(transform.position, direction.normalized, out hit1, sightRange))
    269.             {
    270.                 if (hit.collider.CompareTag("Player")){
    271.                    
    272.                     if (hasseenplayeryet){
    273.                     agent.SetDestination(lastKnownPlayerPosition);
    274.                     } else {
    275.                         player.transform.position = lastKnownPlayerPosition;
    276.                         agent.SetDestination(lastKnownPlayerPosition);
    277.                         hasseenplayeryet = true;
    278.                     }
    279.                 }
    280.             }
    281.         }
    282.         else
    283.         {
    284. if (hasseenplayeryet)
    285. {
    286.     if (!obstacleInWay)
    287.     {
    288.         // No obstacles in the way, chase the player
    289.         lastKnownPlayerPosition = player.position;
    290.         agent.SetDestination(lastKnownPlayerPosition);
    291.     }
    292.     else
    293.     {
    294.         // Obstacle in the way, set walkPoint to player's position
    295.         walkPoint = lastKnownPlayerPosition;
    296.     }
    297. }
    298.  
    299.             Patroling();
    300.         }
    301.     }
    302.  
    303. private void AttackPlayer()
    304. {
    305.     if (isDisabled){
    306.         agent.SetDestination(gameObject.transform.position);
    307.         return;
    308.     }
    309.     // Make sure enemy doesn't move
    310.     agent.SetDestination(transform.position);
    311.  
    312.     // Check line of sight to player
    313.     Vector3 direction = player.position - transform.position;
    314.     RaycastHit hit;
    315.     if (Physics.Raycast(transform.position, direction, out hit, attackRange, ~whatIsGround))
    316.     {
    317.         if (hit.collider.CompareTag("Player"))
    318.         {
    319.             // Attack player
    320.             transform.LookAt(player);
    321.             if (!alreadyAttacked)
    322.             {
    323.                 // Attack code here
    324.                 Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
    325.                 rb.AddForce(transform.forward * 32f, ForceMode.Impulse);
    326.                 rb.AddForce(transform.up * 8f, ForceMode.Impulse);
    327.                 // End of attack code
    328.  
    329.                 alreadyAttacked = true;
    330.                 Invoke(nameof(ResetAttack), timeBetweenAttacks);
    331.             }
    332.             return;
    333.         }
    334.     }
    335.  
    336.     // If player is not in sight, reset the attack status and chase the player
    337.     alreadyAttacked = false;
    338.     ChasePlayer();
    339. }
    340.  
    341.  
    342.     private void ResetAttack()
    343.     {
    344.         alreadyAttacked = false;
    345.     }
    346.  
    347. private void OnDrawGizmosSelected()
    348. {
    349.     Gizmos.color = Color.red;
    350.     Gizmos.DrawWireSphere(transform.position, attackRange);
    351.  
    352.     Gizmos.color = Color.yellow;
    353.     Gizmos.DrawWireSphere(transform.position, sightRange);
    354.  
    355.     Gizmos.color = Color.green;
    356.     Gizmos.DrawWireSphere(transform.position, hearingRange);
    357.  
    358.     Vector3 fovLine1 = Quaternion.AngleAxis(fieldOfViewAngle * 0.5f, transform.up) * transform.forward * sightRange;
    359.     Vector3 fovLine2 = Quaternion.AngleAxis(-fieldOfViewAngle * 0.5f, transform.up) * transform.forward * sightRange;
    360.  
    361.     Gizmos.color = Color.blue;
    362.     Gizmos.DrawRay(transform.position, fovLine1);
    363.     Gizmos.DrawRay(transform.position, fovLine2);
    364.  
    365.     if (walkPointSet)
    366.     {
    367.         Gizmos.color = Color.green;
    368.         Gizmos.DrawSphere(walkPoint, 0.2f);
    369.     }
    370. }
    371. }