[Unity] How to Use Physics.OverlapCapsule

Capsule and Cube Collider

You can use Physics.OverlapCapsule to get two Colliders overlapped with a CapsulCollider as above. This method takes the position and the size of a capsule and returns all Colliders overlapped by the capsule.

You can get the Colliders by configuring a Kinematic Rigidbody Trigger Collier and handling the OnTriggerEnter message, but the method is handy.

The signature without optional arguments of Physics.OverlapCapsule is shown below.

The right figure illustrates the arguments. Each of point0 and point1 has the center of the upper or lower hemisphere. radius has the radius.

The specs of a CapsuleCollider have its center, its height, and its radius. They are different from the arguments of Physics.OverlapCapsule, so you need to convert them.

In the first place, the specs are given in local space, so you have to translate them to world space. Without this translation, Physics.OverlapCapsule can work only when the size of the attached GameObject is 1.

The following code translates the specs from local space to wold space.

The translation uses two methods of the Transform of the attached GameObject. First, TransformPoint translates the center to world space. Then TransformVector translates the radius in x and the height in y to world space.

You can calculate the arguments of Physics.OverlapCapsule from the translated specs as follows.

Notice that the returned Colliders naturally include the CapsuleCollider. You can disable it in advance if you want to exclude it.

Physics.OverlapCapsule is so useful that you can give it a slightly smaller size to exclude just touched Colliders from the result. You can also give it a larger size to get almost colliding Colliders.

By the way, Physics.OverlapCapsule allocates and returns an array to store the results in each invocation, so it causes a lot of allocation when you invoke it on every frame.

In this case, you should use Physics.OverlapCapsuleNonAlloc. This variant stores the results to an array allocated in advance. The usage is shown below.

In this usage, Physics.OverlapCapsuleNonAlloc can detect up to 5 overlapped Colliders. The method takes an array of 5 Colliders allocated outside Update, and stores the results in the array and returns the number of them.

Leave a Reply

Your email address will not be published. Required fields are marked *