Question by
Wolf_dead_inside · Aug 25, 2021 at 10:21 PM ·
raycastnavmeshagentnavagent
Finding nearest enemy with raycast (Nav Mesh Agent)
I want to have different Nav Mesh Agents find each other with raycasts and attack the nearest one not obstructed by a wall. I have something that i think should be working, however the raycasts appear to be hitting their own nav mesh agent hitbox which prematurely stops the raycast. im not sure how to avoid the agent hitbox from being detected. can anyone help?
code is here:
private GameObject FindNearestTarget()
{
GameObject[] targets = GameObject.FindGameObjectsWithTag("Target");
foreach (GameObject target in targets)
{
RaycastHit rayHit = new RaycastHit();
Ray ray = new Ray(transform.position, target.transform.position - transform.position);
if (Physics.Raycast(ray, out rayHit))
{
if (rayHit.transform == this.transform)
{
return null;
}
else if (rayHit.transform == target)
{
return target;
}
else
{
return null;
}
}
return null;
}
return null;
}
private void OnDrawGizmos()
{
GameObject[] targets = GameObject.FindGameObjectsWithTag("Target");
foreach (GameObject target in targets)
{
Ray ray = new Ray(transform.position, target.transform.position - transform.position);
Gizmos.DrawRay(ray);
}
}
note that all of the Nav Mesh Agents have the same tag as they are all instantiated from the same prefab
Comment
Your answer
Follow this Question
Related Questions
Enemy Behaviour And Navigation Being Quite Odd. 0 Answers
How to Keep NavMesh Agent 's Feet from Slipping 2 Answers
pathfinding Error or follow player 0 Answers