Search Unity

  1. Unity 2018.3 is now released.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. We've updated our Terms of Service. Please read our blog post from Unity CTO and Co-Founder Joachim Ante here
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    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:
    32
    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,071
    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

    JapaneseBreakfast

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