- Home /
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
Your answer
![](https://koobas.hobune.stream/wayback/20220613002856im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Follow AI goes up when it gets near me! 0 Answers
my ai wont move 0 Answers
Ai dodge bullets 3 Answers
Enemies Follow Player2 0 Answers
Animal AI Help 0 Answers