• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by artin2007 · Jul 10, 2020 at 12:20 PM · ai problems

How to make AI detect enemy (working script included but need suggestions)

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 using AI_WeaponStats;
 using UnityEngine.UIElements;
 
 namespace AI
 {
 
 
     public class Enemy_AI : MonoBehaviour
     { // this is the script that tells the AI what to do and not to do
         public float hearRadius = 10;
         public float maxRadius;
         public float maxAngle;
         public Transform player;
         public Transform Enemy;
         public NavMeshAgent agent;
         public GameObject weapon;
         public AI_weaponStats weaponStatts;
         public Camera myCam;
         public bool is_inFOV;
         public Collider trigger;
 
 
         private void Start()
         {
             agent = GetComponent<NavMeshAgent>();
             weapon.GetComponent<AI_weaponStats>();
         }
         private void Update()
         {
             float distance = Vector3.Distance(player.position, transform.position);
             if (distance <= hearRadius)
             {
 
             }
             if (inFOV(Enemy, player, maxAngle, maxRadius) == true)
             {
                 is_inFOV = true;
                 agent.SetDestination(player.position);
                 FaceTarget();
                 Shoot(weapon);
             }
             else
             {
                 is_inFOV = false;
             }
         }
         void FaceTarget()
         {
             Vector3 direction = (player.position - transform.position).normalized;
             Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
             transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
         }
         private void OnDrawGizmosSelected()
         {
             Gizmos.color = Color.red;
             Gizmos.DrawWireSphere(transform.position,hearRadius);
         }
         private void OnDrawGizmos()
         {
             Gizmos.color = Color.yellow;
             Gizmos.DrawWireSphere(transform.position, maxRadius);
 
             Vector3 fovLine1 = Quaternion.AngleAxis(maxAngle, transform.up) * transform.forward * maxRadius;
             Vector3 fovLine2 = Quaternion.AngleAxis(-maxAngle, transform.up) * transform.forward * maxRadius;
 
             Gizmos.color = Color.blue;
             Gizmos.DrawRay(transform.position, fovLine1);
             Gizmos.DrawRay(transform.position, fovLine2);
 
             if (is_inFOV == true)
                 Gizmos.color = Color.green;
             else
                 Gizmos.color = Color.red;
 
             Gizmos.DrawRay(transform.position, (player.position - transform.position).normalized * maxRadius);
 
             Gizmos.color = Color.black;
             Gizmos.DrawRay(transform.position, transform.forward * maxRadius);
 
 
 
         }
         public static bool inFOV(Transform checking_object, Transform target, float maxAngle, float maxRadius)
         {
             Collider[] overlaps = new Collider[50];
             int count = Physics.OverlapSphereNonAlloc(checking_object.position, maxRadius, overlaps);
             for (int i = 0; i < count + 1; i++)
             {
                 if (overlaps[i] != null)
                 {
                     if (overlaps[i].transform == target)
                     {
 
                         Vector3 direction_between = (target.position - checking_object.position).normalized;
                         direction_between.y *= 0;
 
                         float Angle = Vector3.Angle(checking_object.forward, direction_between);
                         if (Angle <= maxAngle)
                         {
                             Ray ray = new Ray(checking_object.position, target.position - checking_object.position);
                             RaycastHit hit;
 
                             if (Physics.Raycast(ray, out hit, maxRadius))
                             {
                                 if (hit.transform == target)
                                 {
                                     return true;
                                 }
                             }
                         }
                     }
                 }
 
 
             }
             return false;
         }
 
         public void Shoot(GameObject weapon)
         {
             weapon.GetComponent<AI_weaponStats>().GetWeaponType(weaponStatts.SetWeapontypeHere);
             weapon.GetComponent<AI_weaponStats>().isShooting = true;
 
         }
         public void LastKnownLocation(Vector3 position)
         {
             agent.SetDestination(position);
         }
     }
 }

and here is my gun script that tells the ai where i shot and if in the range hear where i shot from

 using System.Collections;
 using System.Collections.Generic;
 using System.Linq.Expressions;
 using UnityEngine;
 using AI;
 
 
 namespace WeaponStats //For the player 
     // this script sits on the gun and lets us shoot
 {
     public class weaponStatts : MonoBehaviour
     {
         public GameObject WeaponModel;
         public string SetWeapontypeHere;
         public GameObject WeaponMuzzle;
         public float weaponRange = 100f;
         public float fireRate;
         public  float  nextTimeToFire;
         public Camera playerCam;
         public GameObject Player;
         public float burstAmount;
         public GameObject muzzleFlash;
         public GameObject impactEffect;
         public bool isEquiped;
         public float weaponNoise;
 
 
         public void Update()
         {
             if(isEquiped == true)
             GetWeaponType(SetWeapontypeHere);
         }
 
 
         public void GetWeaponType(string SetWeaponTypeHere)
         {
             SetWeaponTypeHere = SetWeapontypeHere;
             switch(SetWeaponTypeHere)
             {
                 case "Auto":
                     AutomaticFire();
                     break;
                 case "Semi":
                     SemiAutoFire();
                     break;
                 case "Pump":
                     PumpFire();
                     break;
                 case "Burst":
                     BurstFire();
                     break;
             }   
         }  
         public void AutomaticFire()
         {
             RaycastHit Hit;
             if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire )
             {
 
                 nextTimeToFire = Time.time + 1/fireRate;
                 if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out Hit, weaponRange))
                 {
                     Debug.Log(Hit.transform.name);
                     Debug.DrawRay(playerCam.transform.position, playerCam.transform.forward, Color.green ,weaponRange);
                     if (Hit.transform.tag == "Enemy")
                     {
                      Destroy(Hit.transform.gameObject);
                     }
                 }
                 GameObject impactGO = Instantiate(impactEffect, Hit.point, Quaternion.LookRotation(Hit.normal));   
                 GameObject muzzleVFX = Instantiate(muzzleFlash, WeaponMuzzle.transform.position, WeaponMuzzle.transform.rotation, WeaponMuzzle.transform );
                 Destroy(impactGO, 0.2f);
                 Destroy(muzzleVFX, 0.2f);
 
                 Collider[] overlaps = new Collider[50];
                 int count = Physics.OverlapSphereNonAlloc(Hit.point, weaponNoise, overlaps);
                 for (int i = 0; i < count + 1; i++)
                 {
                     if (overlaps[i] != null)
                     {
                         if (overlaps[i].transform.tag == "Enemy")
                         {
                             overlaps[i].transform.GetComponent<Enemy_AI>().LastKnownLocation(Hit.point);
                         }
                     }
                 }    
                 
                 Collider[] overlaps2 = new Collider[50];
                 int count2 = Physics.OverlapSphereNonAlloc(WeaponMuzzle.transform.position, weaponNoise, overlaps2);
                 for (int i = 0; i < count2 + 1; i++)
                 {
                     if (overlaps2[i] != null)
                     {
                         if (overlaps2[i].transform.tag == "Enemy")
                         {
                             overlaps2[i].transform.GetComponent<Enemy_AI>().LastKnownLocation(WeaponMuzzle.transform.position);
                         }
                     }
                 }
             }
         }
         
         public void SemiAutoFire()
         {
             RaycastHit Hit;
             if (Input.GetButtonDown("Fire1") && Time.time >= nextTimeToFire)
             {
                 nextTimeToFire = Time.time + 1 / fireRate;
                 if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out Hit, weaponRange))
                 {
                     Debug.Log(Hit.transform.name);
                     if (Hit.transform.tag == "Enemy")
                     {
                         Destroy(Hit.transform.gameObject);
                     }
                 }
                 GameObject impactGO = Instantiate(impactEffect, Hit.point, Quaternion.LookRotation(Hit.normal));
                 GameObject muzzleVFX = Instantiate(muzzleFlash, WeaponMuzzle.transform.position, WeaponMuzzle.transform.rotation);
                 Destroy(impactGO, 0.2f);
                 Destroy(muzzleVFX,0.2f);
             }
         }
         public void PumpFire()
         {
             RaycastHit Hit;
             if (Input.GetButtonDown("Fire1") && Time.time >= nextTimeToFire )
             {
                 nextTimeToFire = Time.time + 1 / fireRate;
                 if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out Hit, weaponRange))
                 {
                     Debug.Log(Hit.transform.name);
                     if (Hit.transform.tag == "Enemy")
                     {
                         Destroy(Hit.transform.gameObject);
                     }
                 }
                 GameObject impactGO = Instantiate(impactEffect, Hit.point, Quaternion.LookRotation(Hit.normal));
                 GameObject muzzleVFX = Instantiate(muzzleFlash, WeaponMuzzle.transform.position, WeaponMuzzle.transform.rotation, WeaponMuzzle.transform);
                 Destroy(impactGO, 0.2f);
                 Destroy(muzzleVFX, 0.2f);
             }
 
         }
         public void BurstFire() // this doesnt work for some reason
         {
      float  currentFire = Time.time + 1/ fireRate;
             RaycastHit Hit;
             if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire && currentFire <= burstAmount )
             {
                 nextTimeToFire = Time.time + 1/fireRate;
                 if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out Hit, weaponRange))
                 {
                     Debug.Log(Hit.transform.name);
                     currentFire++;
                 }
                 GameObject impactGO = Instantiate(impactEffect, Hit.point, Quaternion.LookRotation(Hit.normal));
                 GameObject muzzleVFX = Instantiate(muzzleFlash, WeaponMuzzle.transform.position, WeaponMuzzle.transform.rotation, WeaponMuzzle.transform);
                 Destroy(impactGO, 0.2f);
                 Destroy(muzzleVFX, 0.2f);
             }
 
         }
     }
 }

quick side note this works just fine, all i need is tips and suggestions to make it better.

thanks!!!!!!

Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Update about the future of Unity Answers

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta later in June. Please note, we are aiming to set Unity Answers to read-only mode on the 31st of May in order to prepare for the final data migration.

For more information, please read our full announcement.

Follow this Question

Answers Answers and Comments

130 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multi-Directional Navigation 0 Answers

help with not working AI system 2 Answers

OnDrawGizmos() not working 1 Answer

Enemy model , AI and animation is not working properly 2 Answers

Why do the AI get caught on trees? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges