Search Unity

Can I detect which side of a BoxCollider2D the player hits?

Discussion in 'Getting Started' started by JapaneseBreakfast, Jan 10, 2019.

  1. JapaneseBreakfast


    Sep 7, 2018
    My scene has two GameObjects each one with a BoxCollider2D and a RigidBody2D. None of them have trigger enabled.

    GameObject A is the player, and GameObjectB is an obstacle.

    I'm trying to detect when the player hits either left, right, or bottom sides of the obstacle, so I can kill him/her.

    But if the player jumps on top of the obstacle, he or she can walk on top of it like a platform. So essentially I just don't kill the character and let the Unity Physics engine do its thing.

    I found this link on StackOverflow, but when I try the suggested code, I can't seem to re-write it in a way it works for me. I detect left and right, but when i jump on the obstacle, it's detected as a left or right collision again.

    Code (CSharp):
    1.  void OnCollisionEnter2D(Collision2D  collision)
    2.      {
    3.          Collider2D collider = collision.collider;
    5.          if( == "target")
    6.          {
    7.              Vector3 contactPoint = collision.contacts[0].point;
    8.              Vector3 center =;
    9.              bool right = contactPoint.x > center.x;
    10.              bool top = contactPoint.y > center.y;
    11.          }
    12.      }
  2. Kiwasi


    Dec 5, 2013
    I tend to simply use multiple colliders on separate children GameObjects. You can do this via math if you really need to. But most of the time multiple colliders is the smart way to go.
    JapaneseBreakfast and BlankDeed like this.
  3. JapaneseBreakfast


    Sep 7, 2018
    Thanks Kiwasi! I used multiple colliders and that worked perfectly. Cheers.
    Kiwasi likes this.