Closest object inside Collider?
To make it easier, I'm going to illustrate them on the same plane
Big purple circle = Object of interest
Bigger pink circle = Trigger collider
Green circle = Object with a Trigger collider and kinematic rigidbody
I would need for the big purple circle to know which one of the green objects is the closest. I am using an OnTriggerStay, but as I noticed it does not return all the objects inside the trigger, and so I can't use a foreach to iterate through them. How would I need to go about calculating the distance only once, and not for each OnTriggerStay call? And OnTriggerEnter would not work because once I compute the closest target I move to it then that object is destroyed, then repeat the process. Hope this make sense. Thanks for any help
You might just have to reference all the green dots and find their distance to dark purple. Not sure if the triggers are helping you here at all.
It is helping me, because I have hundreds of the green ones and like ten times less purple ones. They do what they are supposed to at the moment, but they don't go to the closest green circles. And calculating the distance for each green dot will be a way too high complexity for what I would need... I just need a way to iterate through the triggers, just like you would do with colliders with a foreach.
Answer by Yword · Dec 09, 2015 at 02:51 AM
Maybe you can try Physics.OverlapSphere.
Collider[] colliders = Physics.OverlapSphere(center, radius);
Collider nearestCollider = null;
float minSqrDistance = Mathf.Infinity;
for (int i = 0; i < colliders.Length; i++)
{
float sqrDistanceToCenter = (center - colliders[i].transform.position).sqrMagnitude;
if (sqrDistanceToCenter < minSqrDistance)
{
minSqrDistance = sqrDistanceToCenter;
nearestCollider = colliders[i];
}
}
Answer by Adam_Benko · Jan 17, 2019 at 02:19 PM
Hi, how does your script look like ? I am using OnTriggerStay for automatic turret too. It would help me a lot, thanks :)
Your answer

Follow this Question
Related Questions
How I can make my camera keep a distance between two objects? 0 Answers
Modify Draw Distance via Script? 1 Answer
Help with distance between two objects 1 Answer
look at closer 1 Answer
Measure between 2 Objects & show in UI 2 Answers