- Home /
Weird 2d collision behaviour
I have this code in my player which has boxcollider2D and rigidbody2D attached
void OnTriggerEnter2D(Collider2D collider)
{
if(collider == null)
{
Debug.Log("NULLL");
}
}
Some objects are falling from top which have boxcollider2D attached, isTrigger is checked as well.
Now when object collides with player OnTriggerEnter2D is called. Most of the time it triggers as if collider is null and sometime it works fine.
Like if 10 objects are collider with player, 8 times it will give null and 2 times it will work fine. Some times 10 times null.
Is this problem of 2d collision or some unity bug?
Answer by ahmedbenlakhdhar · Dec 03, 2014 at 01:09 AM
The falling game objects are moving so fast that there is no frame which can detect the collision with the player game object, as you see in this example illustration:
You may use Rigidbody.collisionDetectionMode in order to prevent fast moving objects from passing the player game object. Here is a script using it:
void SetPlayerCollisionMode() {
rigidbody.collisionDetectionMode = CollisionDetectionMode.Continuous;
}
void SetFallingObjectCollisionMode() {
rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
}
With the above suggestion results are slightly better. Still it is giving null sometimes.
$$anonymous$$oreover I don't think it is the problem of continuous or discrete because it is giving collider as null. As if player does not have collider.