Rotate AI towards nearest target within sphere collider

Hi,

I (AI Cube) want to be able to move towards the nearest collectible item which is within the sphere Trigger, using onTriggerStay(I think this is what is creating the weird behaviour which I will describe below)

I am using OnTriggerEnter to increment the number of collectible gameObjects, OnTriggerStay to change the rotation to the nearest collectible item and OnTriggerExit to remove the collectible item from the List.

I have also created function to GetRotation of the GetNearest returned game object. The code is as follows -

    private void OnCollisionEnter(Collision collision)
    {
        
        if (collision.gameObject.tag == "Collectible")
        {
            GameController.Instance.ReceiveHealth(gameObject, healthOnPickup);
            areaOfDetection.radius -= healthOnPickup;
            for(int i = 0; i < collectibleList.Count; i++)
            {
                if (collision.gameObject.GetInstanceID() == collectibleList*.gameObject.GetInstanceID())*

{
collectibleList.Remove(collectibleList*.gameObject);*
Destroy(collision.gameObject);
}
}
// remove from list then destroy, otherwise null pointer exception
}
if (collision.gameObject.tag == “Hazard”)
{
GameController.Instance.ReceiveDamage(gameObject, healthOnHazard);
}
UnityEngine.Debug.Log("RBS collided with - " + collision.gameObject.tag);

}

private void OnTriggerEnter(Collider other)
{

// create array to store all collectible objects within sphere, calculate distance to each one go to nearest
if (other.gameObject.tag == “Collectible”)
{
collectibleList.Add(other.gameObject);
// Go to collectible here
// if we detect something go to raycast?
//transform.Rotate(0, GetRotation(GetNearest(collectibleList).transform.position), 0); // lerp for smoothness?
// If something detection in ray get new direction always, but this should be handled in Update ←
Debug.Log(“Enter Trigger - Currently there is/are " + collectibleList.Count + " collectibles within reach”);
}
else
{
// think about putting this in ontriggerstay as well
// do nothing, this is where it should go back and handle from update
}

// we have to deal with object who are actually eaten up // this was completed near Destroy Collider

}

private void OnTriggerStay(Collider other)
{
// Same code applies here. On Trigger Enter rotate towards closest collectible, and on stay keep rotating towards that.
// create array to store all collectible objects within sphere, calculate distance to each one go to nearest
if (other.gameObject.tag == “Collectible”)
{

// collectibleList.Add(other.gameObject); → do not increment this on stay
// Go to collectible here
// if we detect something go to raycast?
transform.Rotate(0, GetRotation(GetNearest(collectibleList).transform.position), 0); // lerp for smoothness?
Debug.Log(“GetNearest is returning this position -” + GetNearest(collectibleList).transform.position);
Debug.Log("The GetRotation function is returning this angle - " + GetRotation(GetNearest(collectibleList).transform.position));
// If something detection in ray get new direction always, but this should be handled in Update ←
Debug.Log(“Stay Trigger - Currently there is/are " + collectibleList.Count + " collectibles within reach”);
}
else
{
// think about putting this in ontriggerstay as well
// do nothing, this is where it should go back and handle from update
}
}

private void OnTriggerExit(Collider other)
{

if (other.gameObject.tag == “Collectible”)
{
collectibleList.Remove(other.gameObject);
Debug.Log(“Exit Trigger - Currently there is/are " + collectibleList.Count + " collectibles within reach”);
} // ^ should this be really here? Answer - Yes, otherwise we will have a problem with for loop in ontriggerenter

}

private float GetRotation(Vector3 collectiblePosition)
{
// Calculate difference between cube and collectible
Vector3 difference = collectiblePosition - transform.position;
float rotationY = Mathf.Atan2(difference.x, difference.z) * Mathf.Rad2Deg;
return rotationY;
// Returns the angle of rotation for cube
}

private GameObject GetNearest(List collectibles)
{
// Find nearest item.
GameObject nearest = null;
float distance = 0;

for (int i = 0; i < collectibles.Count; i++)
{
float tempDistance = Vector3.Distance(transform.position, collectibles*.transform.position);*
if (nearest == null || tempDistance < distance)
{
nearest = collectibles*;*
distance = tempDistance;
}
}

return nearest;
/*
// Remove from list.
items.Remove(nearest);

// Destroy object.
Destroy(nearest.gameObject);
*/
}
OnCollisionEnter is being used for the AI cube and Collectible collider to destroy the collectible object.
The problem here is that, if there is one collectible object with within the detection radius, it will work fine but if there are two or more, the sphere keeps spinning on its axis indefinitely or starts jittering in different rotations[147398-capture.png|147398].
I think a solution to this would be to call the rotation in Update, but not sure if the written code is actually correct for more than one collectible object.

You could try a different approach where you have a singleton that has a list for the positions of each collectible item, or a list for the reference of each item, rather than using the physics engine and holding onto a List in the AI script. The collectible items could have a script on them that notifies the singleton that it has spawned in its start method and the singleton stores its reference in the list.

When the AI wants to find the closest one it asks this singleton for it by passing its position to it and getting a position/reference out.

If the positions are never going to change then you could store that too, instead of going through the ‘transform’ property.

Update on this, using Mathf.approximate and debug I realised what the problem is… silly mistake.

How can I convert the angle to use the same units?

![private void OnTriggerStay(Collider other)
    {
        // Same code applies here. On Trigger Enter rotate towards closest collectible, and on stay keep rotating towards that.
        // create array to store all collectible objects within sphere, calculate distance to each one go to nearest
        if (other.gameObject.tag == "Collectible")
        {
            if (Mathf.Approximately(GetRotation(GetNearest(collectibleList).transform.position), transform.rotation.y))
            {
                // do nothing
                Debug.Log("Do nothing!");
            }
            else
            {
                // change angle
                Debug.Log("Change Angle");
                transform.Rotate(0, GetRotation(GetNearest(collectibleList).transform.position), 0);
            }
            Debug.Log("RBS Angle is " + transform.rotation.y);
            // collectibleList.Add(other.gameObject); -> do not increment this on stay
            // Go to collectible here
            // if we detect something go to raycast?
            /*
            if (GetRotation(GetNearest(collectibleList).transform.position) + 10f >= transform.rotation.y && GetRotation(GetNearest(collectibleList).transform.position) - 10f <= transform.rotation.y)
            {
                Debug.Log("I am in if match");
                // do nothing keep going in same direction
                
            }
            else
            {
                transform.Rotate(0, GetRotation(GetNearest(collectibleList).transform.position), 0);
                Debug.Log("I am updating angle");
                 // lerp for smoothness?
            }
            */    

            Debug.Log("GetNearest is returning this position -" + GetNearest(collectibleList).transform.position);
            Debug.Log("The GetRotation function is returning this angle - " + GetRotation(GetNearest(collectibleList).transform.position));
            // If something detection in ray get new direction always, but this should be handled in Update <-
            Debug.Log("Stay Trigger - Currently there is/are " + collectibleList.Count + " collectibles within reach");
        }
        else
        {
            // think about putting this in ontriggerstay as well
            // do nothing, this is where it should go back and handle from update
        }
    }][1]

I finally managed to solve the issue. I was using OnTriggerStay and running the code only if there is something within that matches the other collider with tag collectible, but I was not doing anything except reading and matching. I wrote this as a function and calling it on each frame from Update, if there are any collectibles in my list.

It works smoothly.