How to Prevent RigidBody from passing through other colliders

Ashish Beuwria picture Ashish Beuwria · Jan 30, 2014 · Viewed 31.4k times · Source

I've got a coin RigidBody and walls around it with box colliders. For trial purpose I've applied the following code to the coin.

private void OnMouseDown() 
{
    rigidbody.AddForce(30.0f, 0f, 5.0f, ForceMode.Impulse);
}

But, sometimes the coin passes through the walls, but when I increase the speed from 30 to 50 points it passes through the walls on the first click. I've googled a lot and still got nothing except for the DontGoThroughThings Script which doesn't work for me or I don't really know how to use it.

I've always added a continuous dynamic on the coin and continuous collision detection on the walls but still doesn't work.

Answer

Matias Gil picture Matias Gil · Jan 30, 2014

the problem with physics collision detection is that sometimes when the speed of an object is too high (in this case as a result of a force added to the rigid body) the collision wont be detected. The reason is that the code you are executing is running at x ammount of steps per seconds so sometimes the rigidbody will go through the collider between one step to another. Lets say you have a ball at 100 miles per hour and a wall that is 1 feet wide, the code will move the ball a determined ammount of feets everytime the code is runned according the physics of it, so the movement of the ball is virtualized but its not a real physical movement so it can happen that from one step to another the ball can move from point a to b and the wall is between those points and as a result the collision will not be detected.

Possible Solutions.

You have a simple solution that wont be as accurate as it should be and a harder one that will be perfectly accurate.

The solution number one will be increasing the colliders size, according to the max speed your coin can get, that way the collider will be big enough so that the collision wont be missed between one frame to another.

The second and harder solution will be adding an auxiliar to your collision detection, some kind of a security check. For example using physical raycast. You can set a raycast to forward direction and determine if that object is an inminent collision, if it does and once the object isnt being collided by the raycast anymore then your collision detection had failed that way you have your auxiliar to confirm that and call the collision state.

I hope it helped and sorry about my english. If you didnt understound it very much i could help you with code but i will need some code from your project.