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 /
  • Help Room /
avatar image
0
Question by KillHour · Oct 29, 2015 at 06:24 AM · collisionmovementoptimization

Most efficient way to find the closest collider to a player?

I'm working on some code to allow the player to mantle up onto short ledges and walls. The way I'm envisioning the system working is the player hovers over the object they want to climb with the mouse and presses a button to try to climb up. Part of that is determining the closest collider within the game object the player wants to climb (a prefab may have more than one collider), so the game knows where to do the rest of the calculations. I have some code for this that works, but it just seems so inelegant/inefficient. Maybe some fresh eyes can improve the algorithm?

 //Find the collider closest to the character
 Collider[] colliders = selectedObject.GetComponentsInChildren<Collider> ();
 Collider closestCollider = colliders[0];
 foreach (Collider collider in colliders)
     {
     Vector3 closestPointA = collider.ClosestPointOnBounds (controller.transform.position);
     Vector3 closestPointB = closestCollider.ClosestPointOnBounds (controller.transform.position);
     float distanceA = Vector3.Distance (closestPointA, controller.transform.position);
     float distanceB = Vector3.Distance (closestPointB, controller.transform.position);
     if (distanceA < distanceB)
         closestCollider = collider;
     }
Comment
Add comment · Show 2
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 centaurianmudpig · Oct 29, 2015 at 10:53 AM 1
Share

I would say that is efficient.

You could sort the array, but you would have to loop through it anyway and if this is the only loop that check for the closest collider then it's not worth doing.

I came across this post whilst looking at Array.Sort(). You could try and compare performance between your existing code and a refactored code that uses a sort. Check out the answer in here: http://answers.unity3d.com/questions/548366/sorting-an-array-of-gameobjects-by-values-inside-t.html

avatar image Socapex centaurianmudpig · Oct 29, 2015 at 11:48 AM 1
Share

I agree, as "inelegant" as that is, I would do it exactly the same way ^_^

If you want some micro optimisation, save the distanceB to an outer float variable, so that way you don't calculate the second distance everytime.

 Collider[] colliders = selectedObject.GetComponentsInChildren<Collider> ();
 Collider closestCollider = colliders[0];
 
 Vector3 closestPointB = closestCollider.ClosestPointOnBounds (controller.transform.position);
 float distanceB = Vector3.Distance(closestPointB, controller.transform.position);

 foreach (Collider collider in colliders)
 {
     Vector3 closestPointA = collider.ClosestPointOnBounds (controller.transform.position);
     float distanceA = Vector3.Distance (closestPointA, controller.transform.position);
 
     if (distanceA < distanceB) {
         closestCollider = collider;
         distanceB = distanceA;
     }
 }

1 Reply

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

Answer by KillHour · Oct 29, 2015 at 05:33 PM

Awesome, thanks guys. Here is the full code for what I ended up doing. I haven't seen any complete code to mantle onto an arbitrary object semi-reliably, so hopefully this helps someone.

 public void Mantle(float maxHeight, float maxDistance) {
 
     Vector3 playerPos = controller.transform.position;
 
     //Check to see if an object is selected
     if (selectedObject)
     {
         //Find the collider closest to the character
         Collider[] colliders = selectedObject.GetComponentsInChildren<Collider> ();
         Collider closestCollider = colliders[0];
         Vector3 closestPointB = closestCollider.ClosestPointOnBounds (playerPos);
         float distanceB = Vector3.Distance (closestPointB, playerPos);
 
         foreach (Collider collider in colliders)
         {
             Vector3 closestPointA = collider.ClosestPointOnBounds (playerPos);
             float distanceA = Vector3.Distance (closestPointA, playerPos);
 
             if (distanceA < distanceB)
             {
                 closestCollider = collider;
                 distanceB = distanceA;
             }
         }
 
         Vector3 closestPoint = closestCollider.ClosestPointOnBounds (playerPos);
 
         //Find the top of closest collider
         float colliderHeight = closestCollider.bounds.max.y;
         
         //Debug.Log (closestCollider + " @ " + colliderHeight);
 
         // Check range of object;
         if (new Vector2 (closestPoint.x - playerPos.x, closestPoint.z - playerPos.z).magnitude > maxDistance || // Too far away!
             colliderHeight - playerPos.y > maxHeight || //Too high!
             colliderHeight - playerPos.y < -1) //Can't mantle down!
             return;
 
         /*
         Debug.DrawRay(new Vector3 (closestPoint.x + 0.0F, colliderHeight, closestPoint.z + 0.0F), new Vector3 (0.0F, 2.5F, 0.0F), Color.red, 2.0F);
         Debug.DrawRay(new Vector3 (closestPoint.x + 0.5F, colliderHeight, closestPoint.z + 0.5F), new Vector3 (0.0F, 2.5F, 0.0F), Color.green, 2.0F);
         Debug.DrawRay(new Vector3 (closestPoint.x - 0.5F, colliderHeight, closestPoint.z - 0.5F), new Vector3 (0.0F, 2.5F, 0.0F), Color.blue, 2.0F);
         Debug.DrawRay(new Vector3 (closestPoint.x - 0.5F, colliderHeight, closestPoint.z + 0.5F), new Vector3 (0.0F, 2.5F, 0.0F), Color.yellow, 2.0F);
         Debug.DrawRay(new Vector3 (closestPoint.x + 0.5F, colliderHeight, closestPoint.z - 0.5F), new Vector3 (0.0F, 2.5F, 0.0F), Color.magenta, 2.0F);
         Debug.DrawRay(playerPos, new Vector3 (0.0F, 4.0F, 0.0F), Color.white, 2.0F);
         */
 
         // Check if it is reasonable to climb on the area selected.  This doesn't guarantee the player will fit, just that there is enough room to try.
         if (Physics.Raycast(new Vector3 (closestPoint.x + 0.0F, colliderHeight - 0.01F, closestPoint.z + 0.0F), Vector3.up, 2.5F) ||
             Physics.Raycast(new Vector3 (closestPoint.x + 0.5F, colliderHeight - 0.01F, closestPoint.z + 0.5F), Vector3.up, 2.5F) ||
             Physics.Raycast(new Vector3 (closestPoint.x - 0.5F, colliderHeight - 0.01F, closestPoint.z - 0.5F), Vector3.up, 2.5F) ||
             Physics.Raycast(new Vector3 (closestPoint.x - 0.0F, colliderHeight - 0.01F, closestPoint.z + 0.0F), Vector3.up, 2.5F) ||
             Physics.Raycast(new Vector3 (closestPoint.x + 0.0F, colliderHeight - 0.01F, closestPoint.z - 0.0F), Vector3.up, 2.5F) ||
             Physics.Raycast(playerPos, Vector3.up, 4F))
             return; // No room to fit!
 
         //Debug.Log ("Can mantle this");
 
         Vector3 mantlePoint = new Vector3 (closestPoint.x, colliderHeight + 2.33F, closestPoint.z);
 
         //Make character face object being mantled
         controller.transform.LookAt(new Vector3 (closestPoint.x, playerPos.y, closestPoint.z));
 
         StartCoroutine (moveCharacter (controller, mantlePoint, mantleMaxTime));
         CrouchCharacter();  //This allows character to climb up to tight areas; e.g., an air vent or plenum
     }
 }
 
 public IEnumerator moveCharacter (CharacterController character, Vector3 newPos, float maxTime) {
     //Debug.Log ("Trying to move character to " + newPos);
 
     //Make sure the player doesn't have any movement going into the mantle or things break
     //I also disable movement input while mantling
     moveDirection = Vector3.zero;
 
     //We don't want gravity to interfere with our climbing
     float oldGravity = gravity;
     gravity = 0.0F;
 
     //Start moving player up only.
     float t = 0.0F;
     while (t < maxTime && character.transform.position.y < newPos.y){
         Vector3 dir = (newPos - character.transform.position).normalized * mantleSpeed;
         //Debug.Log (dir);
         character.Move (new Vector3 (0, dir.y, 0));
 
         //Once player is in stair-height range of y, we can start moving them forward
         if (character.transform.position.y > newPos.y - 1)
             character.Move (dir);
 
         t += Time.deltaTime;
         yield return new WaitForFixedUpdate();
     }
 //Nudge the player just a little bit to make sure they stay on.
 
         for (int i = 0; i <= mantleNudgeFrames; i++) {
             character.Move (new Vector3 (nudgeDirection.x, 0, nudgeDirection.y).normalized * mantleSpeed);
             yield return new WaitForFixedUpdate();
         }
 
     gravity = oldGravity;
 
 //Attempt to stand back up
 if (canStand)
     UncrouchCharacter ();
 
 yield break;
 }




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

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

37 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

Related Questions

Ray casting collision detection, not working for moving right. 0 Answers

How to SHOOT an object on a curved path without using Rigidbody 2 Answers

How can I remove movement or camera rotation in one direction with a trigger 0 Answers

Make object(s) stack vertically. 0 Answers

making movement stop at object collision 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