- Home /
Keep Sphere Collider within Capsule Collider
Hi all,
I'm trying simply drag a sphere around, whilst keeping it bound within a capsule collider.
If I use the bounds of the capsule to check if the point I want to move the sphere is it will work only if the capsule isn't rotated (I gather it tests the bounding box around it and therefore it means I can move the sphere outside of the capsule).
Using the following code to move the sphere, and test if it's within the capsule I get the following results:
[SerializeField]
Collider m_CapsuleCollider;
void Update ()
{
if(Input.GetMouseButton(0))
{
Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, (transform.position - Camera.main.transform.position).z));
if(IsPointWithinBounds(pos))
{
transform.position = pos;
}
}
}
bool IsPointWithinBounds(Vector3 point)
{
return m_CapsuleCollider.bounds.Contains(point);
}
As you can see here is the sphere hitting the bounding box of the capsule (when it is not rotated).
Using the same code, when the capsule is rotated and those the bounding box's edges move outside of the capsule, the sphere is allowed to move outside of it.
My aim is to be able to drag the sphere around the inside of the capsule collider, without any of the sphere moving outside of it.
Any help would be most appreciated.
Your answer
![](https://koobas.hobune.stream/wayback/20220612080513im_/https://answers.unity.com/themes/thub/images/avi.jpg)