- Home /
Trigger on entering field of view
Hey guys,
I want to make an AI that shoot at target if it within the field of view (360) example:
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?
Thanks.
Yes there is and it's probably raycast. Is there a reason you dont want to use the Raycast? Its the perfect use case for this because you want to create some line of sight. And thisis basically what raycast is as well. I wouldn't worry to much about performance issues or anything if that's what you are worried about.
Answer by Zentiu · Mar 20, 2020 at 11:02 PM
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. :P
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.
I hope this is helpful. If not, let me know.
Hey Zentiu, first of all thank you for reply. You suggest to make a selective check on the enemies who are relevant. I will implement your suggestion with an interval of 60 checks per sec, If I won't find a more efficient solution.
Your answer
Follow this Question
Related Questions
How do I trigger an event (health loss) only once? 3 Answers
Trigger event by bringing controller to my Head,Swap to Camera Mode 0 Answers
Toggle onPointerDown event 2 Answers
Scoring System for Pinball 0 Answers