user21909947
user21909947

Reputation:

Slime Head and Body both trigger OnCollisionEnter2D when Player lands only on top of Slime Head in Unity 2D game

In my Unity 2d game, I have a Player object which has attached a BoxCollider2d and a rigidbody2d.

I have a slime game object which has a rigidbody, a box collider on its body, and a script attached called SlimeBody which has one function for OnCollisionEnter2D that Debugs.Log("BODY") if the Collision object has a "Player"

In this slime object, I have an empty child game object named "Slime Head" which has a box collider inside and a script called SlimeHead. The box collider is of course put so it covers the slimes head, and is sitting right above the parents boxcollider2d where they are not making contact. The script inside the slime head object Debugs.Log ("HEAD") inside an OnCollisionEnter2d function as well if the collision object has a tag called Player as well.

My issue is, when i jump on top of the slime, both the head and body debug.log, even when I am sure I am landing striclty only on top of the slimes head.

If I hit the slime from the side where I make contact withthe slimes bodys sides, only the Body debug log fires. But when I STAND ontop of the slimes head and jump on it, both fire. Why??

Ive checked and neither colliders collide with eachother, and there is no way that the player is touching the bodys box collider yet both are getting ran inside OnCollisionEnter

Upvotes: 0

Views: 51

Answers (1)

shingo
shingo

Reputation: 27414

Sorry a reproducible project is not needed, The OnCollisionEnter2D event will be sent to Rigidbody2D too, and your body object has both a rigidbody and a box collider attached.

To solve the problem you can move the body collider and the script to a child object like this:

slime (rigidbody)
 ├── head (collider, script)
 └── body (collider, script)

Another method is to compare the otherCollider value in your script:

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.otherCollider != GetComponent<Collider>())
        return;
}

Upvotes: 1

Related Questions