on the basic method, I put a circle on the AI GameObject, with a collide trigger, so I could call a function
that start the AI shooting.
I want to improve the function, So the AI would know if it can hit the target directly or not.
in the example, the orange circle cannot be attacked, but if it would move to the red circle,
the AI would start to attack.
Is there an implementation to do it without checking on every sence update, with Ray if the target within the field of view?
If i were you i would give your AI another collider and set it to trigger. I would set this trigger to the range of what the AI should look for at max range. Then the AI will have a list of ‘targets’ that enter the collider and set a raycast. if there is something in front of them, ignore it. if the raycast returns the enemy that he has in his list then unleash hell.
raycasthit hit;
vector3 direction = transform.lookat(firstTargetEnteredTrigger.transform.position);
if(physics.raycast(AI.transform.position, direction, AIRange, out hit))
{
if(hit.collider.gameObject.Tag == "enemy")
{
//Unleash Hell!
}
}
Don’t forget to add:
public void OnTriggerEnter(collision col)
{
if(col.gameObject.Tag == "Enemy")
{
//Create this list and when anyone enters that is an enemy, add it. Do NOT forget to remove them afterwards when the enemy dies or goes out of trigger like shown below.
listOfEnemies.add(col.gameObject);
}
Public void OnTriggerExit(Collision col)
{
if(col.gameObject.Tag == "Enemy" && listOfEnemies.contains(col.GameObject))
{
listOfEnemies.remove(col.GameObject);
}
}
You need to check every frame or if you set up a timer instead if the enemy changed position like ‘no longer behind a wall or whatever’ but at least you now have a list f enemies for this AI that happen to be in range and let the AI handle who to shoot for first in code. Just don’t forget to create that ‘listOfEnemies’ list.