- Home /
How to accurately detect collision?
So I had a throwable fire grenade in my game that will bounce off the wall and explode when touching the ground. For my grenade, I set the rigidbody's collision detection to continuous and have a boxcast under it to check if it touches the ground. But sometimes when it moved so fast it would bounce back instantly in the next frame so my boxcast wouldn't work.
First frame: (the red box below the grenade is the boxcast, the grenade is falling) Next frame: (the grenade bounce back off without actually touch the ground, so the boxcast isn't triggered)
A simple fix that I know of is that you can set the objects like the ground and the wall with continuous collision detection but its pretty costly, I'll try finding a better fix right now, ill reply if I find something.
@mzaidan1996 I don't think that is the solution. Sorry for not describe the problem clearly (I've just updated the question). The problem is in the first frame the object is falling very fast and about to touches the ground. In the next frame, the physics engine will calculate and decide that the object should already hit the ground and bounce it back off. I think the collision at this time still gets detect and some function like OnTriggerEnter, OnCollisionEnter... still get called but the problem is the boxcast as you see above hasn't hit the ground so it will not trigger.
$$anonymous$$ake sure you do the box cast in FixedUpdate() rather than Update(), and use Physics2D.BoxCast rather than Physics.BoxCast if it's 2d.
You could try reducing the fixed timestep in project settings. It might be slow in the editor if you set it to like 1/180 but physics is a lot faster in builds for me.
Answer by Long2904 · Aug 06, 2020 at 06:17 AM
Decrease the fixed time step to something like 0.01 or 0.005 and change the yield return null to yield return WaitForFixedUpdate().
Answer by tuinal · Aug 04, 2020 at 03:38 AM
Simple option in edit>project settings>physics reduce 'fixed time step'. This runs the physics simulation more quickly at the cost of performance.
I think the best solution is to ditch the boxcast and use OnCollisionEnter2D instead. In OnCollisionEnter2D, if you want it to only explode when it hits the floor, do if(Vector2.Angle(Vector2.Up, collision.contacts[0].normal)<10f);
or similar.
@tuinal Firstly, I thought the fixed time step is for the fixed update and my boxcast got called and updated in a coroutine that yield return null so I don't think this will fix anything. Secondly, I create and access the grenade gameobject through code (from another gameobject) in runtime so access to its update or OnCollsionEnter2D function is not possible. Do you have any other ideas? Edit: Also the timestep setting is in Time, not Physics, and I'm currently using Physics2D.