Skip to main content
Added examples for ClosestPointOnBounds and OverlapSphere
Source Link

Unity provides this functionality out of the box with Collider.ClosestPointOnBounds and Rigidbody.ClosestPointOnBounds (for compound colliders).

Testing whether an object is in range is as simple as:

bool IsInRange(GameObject target, Vector3 origin, float rangeSquared) {
    Vector3 closest = target.GetComponent<Rigidbody>().ClosestPointOnBounds(origin);
    
    return ((closest - origin).sqrMagnitude <= rangeSquared);
}

(Note that I'm using sqrMagnitude and compare the result to "range squared" because it's faster, especially if the range doesn't change often)

Or, as DMGregory pointed out, you could use Physics.OverlapSphere / Physics.OverlapSphereNonAlloc to check with a sinlge call:

void ProcessAllInRange(Vector3 center, float radius)
{
    Collider[] hits = Physics.OverlapSphere(center, radius);
    int i = 0;
    while (i < hits.Length)
    {
        //do work
        i++;
    }
}

It is worth mentioning that Physics.OverlapSphere (as far as I can tell) checks for actual collisions, while Rigidbody.ClosestPointOnBounds uses the compound collider's (axis aligned) bounding box.

Unity provides this functionality out of the box with Collider.ClosestPointOnBounds and Rigidbody.ClosestPointOnBounds (for compound colliders).

Unity provides this functionality out of the box with Collider.ClosestPointOnBounds and Rigidbody.ClosestPointOnBounds (for compound colliders).

Testing whether an object is in range is as simple as:

bool IsInRange(GameObject target, Vector3 origin, float rangeSquared) {
    Vector3 closest = target.GetComponent<Rigidbody>().ClosestPointOnBounds(origin);
    
    return ((closest - origin).sqrMagnitude <= rangeSquared);
}

(Note that I'm using sqrMagnitude and compare the result to "range squared" because it's faster, especially if the range doesn't change often)

Or, as DMGregory pointed out, you could use Physics.OverlapSphere / Physics.OverlapSphereNonAlloc to check with a sinlge call:

void ProcessAllInRange(Vector3 center, float radius)
{
    Collider[] hits = Physics.OverlapSphere(center, radius);
    int i = 0;
    while (i < hits.Length)
    {
        //do work
        i++;
    }
}

It is worth mentioning that Physics.OverlapSphere (as far as I can tell) checks for actual collisions, while Rigidbody.ClosestPointOnBounds uses the compound collider's (axis aligned) bounding box.

Source Link

Unity provides this functionality out of the box with Collider.ClosestPointOnBounds and Rigidbody.ClosestPointOnBounds (for compound colliders).