How Do You Overlap a CapsuleCollider in Unity? (Dev Log #3)
Unity physics methods like BoxCast or OverlapCapsule are incredibly useful when you need to do some custom physics calculations in your game. In my experience, you often need to use these methods in conjunction with colliders on a Rigidbody to see what they may overlap if you move them.
Unfortunately, the Physics API does not provide an easy way to take a local-space Collider and convert it into the appropriate world-space parameters expected by methods like Physics.OverlapCapsule.
For example, here is a simple MonoBehaviour that tries to check each frame if its CapsuleCollider is overlapping anything in the scene:
It is possible to calculate these world-space parameters yourself manually of course, but it is tedious and error prone because the transform of the Collider or its parent can change rotation, scale, or position arbitrarily.
In the course of developing Just In Time Incorporated I got annoyed enough with this problem to write an extensions class that contains the world-space conversions for BoxCollider, SphereCollider, and CapsuleCollider. The class also contains wrapper methods that take a Collider and call BoxCast/SphereCast/etc for you.
The class from above would now look like:
You are also free to use the ToWorldSpaceCapsule/Box/Sphere extension methods yourself of course:
Get it here on Github (MIT Licensed):