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;
}
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
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;
}
}
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;
}
Your answer
Follow this Question
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