Hey, I got this problem: the player character has a cone-shaped trigger in the forward direction. When an enemy enters the trigger, the character automatically looks at (rotates so that the forward direction is towards) the enemy. If works perfectly with one target, but if there are two enemies inside the trigger the script no longer works. From what I can tell, it makes a mean value out of all the enemy transforms and looks at it - not sure if that is the case.
Ideally, I’d like to have my character look at the first enemy that enters the trigger. If that enemy is killed/gets out of the trigger, it should look toward the second enemy that entered the trigger (if the case) and so on. In case there are no other enemies in the trigger, just keep the current rotation.
It’s not actually averaging the positions of multiple colliders, but the end result is similar. OnTriggerStay is called every frame for every collider within the trigger. So what’s happening is it gets called it for one collider, the player turns a bit toward it, then it’s called for the next collider and the player turns back toward that one a bit.
There’s a few ways to do this, as most things are, but this is basically how I’d do this. Use OnTriggerEnter to store a reference when the enemy enters the trigger zone and add it to a list. Use OnTriggerExit to remove the reference when it leaves. Then use FixedUpdate to look toward the first enemy in the list.
(Typed directly into answer window, but should get you close)
using System.Collections.Generic; //Needed to use Lists
List< Collider > enemiesInLookRange = new List< Collider >();
OnTriggerEnter(Collider col)
{
if(!enemiesInLookRange.Contains(col) && (col.gameObject.tag == "Enemy"))
{
enemiesInLookRange.Add(col);
}
}
OnTriggerExit(Collider col)
{
if(enemiesInLookRange.Contains(col))
{
enemiesInLookRange.Remove(col);
}
}
FixedUpdate()
{
if(enemiesInLookRange.Count > 0)
{
//Look at target enemiesInLookRange[0].transform;
}
}