- Home /
Using a trigger collider to detect enemies.
I am using a sphere collider, set to isTrigger=false, to create a hashtable of all the enemies in range of my player. My code looks like this:
void OnTriggerEnter(Collider c) { if(c.isTrigger) return;
if(c.gameObject.tag == "Unit")
{
_knownEnemies[c.transform.GetInstanceID()] = c.gameObject;
}
}
void OnTriggerExit(Collider c) {
if(c.isTrigger)
return;
if(c.gameObject.tag == "Unit")
{
_knownEnemies.Remove(c.transform.GetInstanceID());
}
}
The line:
if(c.isTrigger)
return;
Is necessary as currently the sphere collider is triggering the OnTriggerEnter event when it collides with other sphere colliders (also set to isTrigger = true) which is undesirable.
1) Is there a neater way of making it so the trigger events are only called when a collider enters a trigger, not when a trigger enters a trigger?
2) Would it be faster to just use Physics.SphereCast every update instead? This gets around using triggers.
Answer by Jean-Fabre · Apr 28, 2011 at 05:12 AM
Hi,
You should maybe try using the physics collision Matrix
this will allow you great control over this kind of confinment.
Regards SphereCast alternative. thyt would start to make sense if you only check every nth frame or every x seconds. cause I don't think it's critical to check every frame about enemy range detection. find the fastest way for an enemy and player to come in range and define a minimum threshold timer and then SphereCast would be I think a good option. But every frame, I would stick with the built in collision system.
Bye,
Jean