Prevent movement into a collider whilst using custom movement script

Hey guys,

I have a movement script that moves a capsule(containing the camera) but does so via rotations and movements of it’s parent objects. The movements are working fine, but now I would like to introduce collisions to the camera so it can’t go through various scenery.

My problem is that I want to prevent the capsule from making any movement that would cause a collision, however it won’t know it’s going to collide until it does so, thus leaving the capsule in the scenery.

I initially tried completing the movement and then checking my collision flag, if a collision occurred then reverse the movement, obviously this solution produces a camera vibration and is terrible. My next thought is to have a “test” capsule that completes the movement, checks for collision, if yes then reverse the movement, if no then have the camera capsule match it’s location.

But this is starting to sound rather hacky and I’m wondering if there is a simpler way?

Many thanks in advance.

Before moving the object, use Physics.CapsuleCast with the same direction and length that the capsule would be moving without collision. It works very much like a raycast, the only difference is that instead of moving a point through space to see if it hits anything, it moves an entire capsule through space.

If CapsuleCast returns false, then it didn’t hit anything so the capsule is fine moving the entire distance it wanted to. Otherwise, using the information stored in the RaycastHit (the out parameter), it will be possible to respond to the collision however you wish.