What is the best way to prevent a physics object from going through thin colliders?


What is the best way?
Here is an example from my project…

I have a grenade, (well, it’s just a ball really), and I throw it (at full power) towards my door and because the ball moves so fast and the door is so thin, the physics update will position it behind the door and not detecting the collision. I thought the PhysX calculations automatically compensated for this… but I guess not.

I want to avoid using the linecast/re-position method if possible as that is just a line, not a volume check… meaning it will clip corners.

Physics is updated 50 times per second. If your projectile is moving so fast that between 2 checks it completely passes the door the engine cannot really catch that.

simmilar question

Quote: To fix this, you can use the built-in Unity tools - particularly, setting a moving object like your plank to “Continuous Dynamic” collision in its rigidbody settings, and setting the floor to “Continuous” collision. If you are using mobile devices though, this will probably be too expensive. In those cases, you can also just use thicker objects - if you need to use a thin plank, you can also make the floor thicker.

Usually the best sollution for really fast-moving objects is using raycast (even if setting the dectecion at continuous dynamic it can still fail and it can hurt your performance).

The script logic you need is something like this:

At start:

  • We add the grenade’s position to a variable, let’s call it lastPos

Each frame (in update):

  • We add the new grenade’s position to a variable (newPos)
  • Then, we create a rayCast from lastPos to newPos
  • We check if the raycast collides with anything from lastPos to newPos
  • if it has collided, a collission has been skipped between frames due to the grenade’s speed
  • We change the position of the grenade to stay behind the collider (not on the collider but a little far from it, to ensure the collision on the next frame
  • You might want to reduce the grenade’s velocity at this point as well
  • Lastly, you set lastPos to the new grenade’s position

As you can see, the problem is the continuous collision detection the raycast is doing (this might hurt performance as well), but I have found this method to be the best sollution for fast moving objects. (When i do bullets i usually do it only with raycast and totally forget about gameObjects, but in the case of a grenade this’ll do fine)

I’m sorry I cannot write an script for you, but It’s been a time since I last used raycast and colliders and I wouldn’t write it well.

Hope it helped!