- Home /
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[i].gameObject.GetInstanceID())
{
collectibleList.Remove(collectibleList[i].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<GameObject> 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[i].transform.position);
if (nearest == null || tempDistance < distance)
{
nearest = collectibles[i];
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.
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.
Update on this, using $$anonymous$$athf.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 ($$anonymous$$athf.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]
[1]: /storage/temp/147406-capture.png
Answer by firepro20 · Oct 15, 2019 at 08:52 AM
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.
Answer by Tobychappell · Oct 13, 2019 at 09:16 PM
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.
That is correct positions will stay the same. I have used a rubber ducky approach and realised where the issue is and now I'm trying to solve it.
The issue is located in the OnTriggerStay, I was updating / incrementing the current angle by the new angle from the returned GetRotation method.
I added an if statement to check that if the angle is within a certain range of the current angle, then do not get a new angle from the method, so I want to do it as follows, however still not working, probably something incorrect in the logic.
I want to call the method if the current angle is more than +- 10 degrees.
if (GetRotation(GetNearest(collectibleList).transform.position) >= transform.rotation.y + 10f && GetRotation(GetNearest(collectibleList).transform.position) <= transform.rotation.y - 10f)
{
Debug.Log("I am in if match");
// do nothing keep going in same direction
}
else
{
Debug.Log("I am updating angle");
transform.Rotate(0, GetRotation(GetNearest(collectibleList).transform.position), 0); // lerp for smoothness?
}
Also don't use distance to sort,use sqrmagnitude at it is significantly more performant than distance, and gives an identical result.
Your answer
Follow this Question
Related Questions
How to fix box drop via code animation? 2 Answers
My object is translating with speed but does not stop... 1 Answer
My "Lava " script doesnt work 2 Answers
Trying to position a world space menu in front of the camera whilst ignoring the camera's tilt angle 1 Answer
Bayonet Action Transform 0 Answers