Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

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

  1. JapaneseBreakfast

    JapaneseBreakfast

    Joined:
    Sep 7, 2018
    Posts:
    44
    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;
    4.  
    5.          if(collider.name == "target")
    6.          {
    7.              Vector3 contactPoint = collision.contacts[0].point;
    8.              Vector3 center = collider.bounds.center;
    9.              bool right = contactPoint.x > center.x;
    10.              bool top = contactPoint.y > center.y;
    11.          }
    12.      }
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    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.
     
  3. JapaneseBreakfast

    JapaneseBreakfast

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