Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by firepro20 · Oct 13, 2019 at 08:10 PM · transform.positionontriggerstayrotatetowardstransform.forwardvector3.distance

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 rotationsalt text.

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.

capture.png (255.8 kB)
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image firepro20 · Oct 13, 2019 at 11:37 PM 0
Share

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

capture.png (32.9 kB)

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image firepro20 · Oct 13, 2019 at 11:19 PM 0
Share

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?
             }
avatar image mikawendt firepro20 · Oct 14, 2019 at 10:14 AM 1
Share

Also don't use distance to sort,use sqrmagnitude at it is significantly more performant than distance, and gives an identical result.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

114 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges