Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
9
Question by thusitha · Sep 02, 2014 at 11:07 AM · boxcollider2d

detect side of collision in box collider 2d?

I'm new to unity3d. I have seen this question has been asked in many places but I couldn't figure out how to solve this problem. I have two objects with box collider 2d target and a ball with Circle Collider 2d. I want to detect the side of target box when ball hits the target. simply my question is how to detect the side ball hits in the box(top,left,bottom or right). I could get the the position of the hitting object with following code but it's useless.

 void OnCollisionEnter2D(Collision2D  collision) 
     {
         Collider2D collider = collision.collider;
 
          if(collider.name== "target")
         {
             print(collider.name);
                     
             ContactPoint2D contact = collision.contacts[0];
             Vector3 pos = contact.point;
                  
             print(pos);
         }
     }
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Vasile-Peste · Aug 01, 2019 at 04:09 PM 0
Share

Take a look at this https://www.malgol.com/how-to-detect-collision-side-in-unity-2d/ should work with any collider. Just download and import the code.

4 Replies

· Add your reply
  • Sort: 
avatar image
13

Answer by kacyesp · Sep 02, 2014 at 11:26 AM

Use collider.bounds.center and compare it with the point.

 void OnCollisionEnter2D(Collision2D  collision) 
     {
         Collider2D collider = collision.collider;
  
         if(collider.name == "target")
         { 
             Vector3 contactPoint = collision.contacts[0].point;
             Vector3 center = collider.bounds.center;
 
             bool right = contactPoint.x > center.x;
             bool top = contactPoint.y > center.y;
         }
     }


Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image thusitha · Sep 05, 2014 at 11:01 AM 0
Share

Thank you for the effort @kacyesp. I used ray Physics2D.Linecast to draw a line and detect the side. thank you again for the answer.

avatar image nanthsree22 · Mar 30, 2015 at 05:29 AM 0
Share

How would I do this for an OnTriggerEnter2D function?

avatar image alexjhones286 · Jan 20, 2018 at 06:42 PM 1
Share

Obrigado amigo'. Brasil aqui'. :)

avatar image Kunal23082003 · Mar 27 at 02:29 PM 0
Share

I tried this script.But whenever the object collides from the top and bottom,The right collider gets hits.and when the object collides from left and right the script is working.When I removed the horizontal collision, Vertical collisions are working just fine.Anyone know why both of them are not working together

avatar image
4

Answer by Kodekool · Oct 01, 2015 at 12:02 PM

This is going to be a little basic of me, but please forgive my ignorance, can anyone explain a bit as to why this works? or point me to a resource where I can read more about it. i'm a little confused.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ValderZhu · Mar 24, 2016 at 03:04 AM 4
Share

Collision Refer to the image. The rectangle is your collider and the circle is the inco$$anonymous$$g object. If ( contactPoint.x > center.x ), this means that the center of circle is on the right of center of rectangle. If (contactPoint.y > center.y ), the center of circle is on the top of center of rectangle. You may want to check the coordinates with stronger conditions, like:

 void OnCollisionEnter2D(Collision2D  collision) 
     {
         Collider2D collider = collision.collider;
         bool collideFromLeft;
         bool collideFromTop;
         bool collideFromRight;
         bool collideFromBottom;
         int RectWidth = this.GetComponent<Collider2D> ().bounds.size.x;
         int RectHeight = this.GetComponent<Collider2D> ().bounds.size.y;
         int circleRad = collider.bounds.size.x;
 
         if(collider.name == "target")
         { 
             Vector3 contactPoint = collision.contacts[0].point;
             Vector3 center = collider.bounds.center;
 
             if (contactPoint.y > center.y && //checks that circle is on top of rectangle
                 (contactPoint.x < center.x + RectWidth / 2 && contactPoint.x > center.x - RectWidth / 2)) {
                 collideFromTop = true;
             }
             else if (contactPoint.y < center.y &&
                 (contactPoint.x < center.x + RectWidth / 2 && contactPoint.x > center.x - RectWidth / 2)) {
                 collideFromBottom = true;
             }
             else if (contactPoint.x > center.x &&
                 (contactPoint.y < center.y + RectHeight / 2 && contactPoint.y > center.y - RectHeight / 2)) {
                 collideFromRight = true;
             }
             else if (contactPoint.x < center.x &&
                 (contactPoint.y < center.y + RectHeight / 2 && contactPoint.y > center.y - RectHeight / 2)) {
                 collideFromLeft = true;
             }
         }
     }



collision.png (43.8 kB)
avatar image Kodekool ValderZhu · Mar 24, 2016 at 05:13 PM 0
Share

Thanks. I'd actually done a lot of reading on this since posting the question so I did understand, but I really appreciate you taking the time to give me this explanation.

avatar image brdavid_unity · Jan 19, 2020 at 05:59 PM 0
Share

From researching and program$$anonymous$$g this, this will not work. The code as it stands cannot deter$$anonymous$$e if the contact is truly on the bottom when it could actually be on the lower left or lower right and still be true for all checks for the bottom condition.

One Idea that I have is to find the angle from the center to the point of contact. If that angle appears in a specific part of the box, we have our side.

For example from the center to the topleft and topright there is an angle between the two lines which connect to these corners from the center. If my contact point is between these two angles then I know exactly what side I am on. I can assume a side if the angle is equal.

avatar image
0

Answer by brdavid_unity · Jan 19, 2020 at 09:47 PM

For the curious, I solved this problem using the following code

     private string WhatSideOfTheColliderWasHit(Collider2D collision)
     {
         Vector2 PointOnBoxHit = collision.ClosestPoint(transform.position);
         Vector2 centerOfObject = collision.bounds.center;
         float xMinPoint = Mathf.Abs((collision.bounds.size.x/2) - centerOfObject.x);
         float xMaxPoint = Mathf.Abs(xMinPoint + collision.bounds.size.x);
         float yMinPoint = Mathf.Abs((collision.bounds.size.y / 2) - centerOfObject.y);
         float yMaxPoint = Mathf.Abs(yMinPoint + collision.bounds.size.y);
 
         if (PointOnBoxHit.x >= xMinPoint && PointOnBoxHit.x <= xMaxPoint && Approximately(yMaxPoint, PointOnBoxHit.y, .1f))
             return "Bottom";
         else if (PointOnBoxHit.x >= xMinPoint && PointOnBoxHit.x <= xMaxPoint && Approximately(yMinPoint, PointOnBoxHit.y, .1f))
             return "Top";
         else if (PointOnBoxHit.y >= yMinPoint && PointOnBoxHit.y <= yMaxPoint && Approximately(xMaxPoint, PointOnBoxHit.y, .1f))
             return "Right";
         else
             return "Left";
     }

The basic idea is that I grab the closest point on the collider box where the collision happened. I then get the calculate the min/max of x and y of this particular box. I then simply compare my point to these min/max values. It tells exactly what side of the box I am on.

Also Approximately is my own function that basically checks to see if the two values are within a threshold. It's like Mathf.Approximately but I can control the epsilon.

Edit: You may have a problem with certain blocks returning size = 0,0,0 in some cases. If this happens then just go after size from the component

 Vector3 size = collision.gameObject.GetComponent<BoxCollider2D>().size;

That fixed the issue for me. Then for the code above that calls for size, just replace collision.bounds.size with just size.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Tioboon · Sep 26, 2021 at 03:36 PM

Here is a easier way to make that:

  • Get the collision point by ClosestPoint (https://docs.unity3d.com/2019.1/Documentation/ScriptReference/Collider2D.ClosestPoint.html)

  • Get the distance from collision object center (using bounds.center) to closestPoint

  • Get the angle of the distance

  • Draw a box somewhere and trace lines to determine wich part of the box will make a different action.

  • Create a enum for each one of them.

  • Check the angles and return the enum.

Here is the code:

 private static CollisionSide CheckIfFloorIsUnder(Collider2D thisCollider, Collider2D otherCollider)
     {
         var closestPoint = otherCollider.ClosestPoint(thisCollider.bounds.center);
         var distance = closestPoint - (Vector2)otherCollider.bounds.center;
         var angle = Vector2.Angle(Vector2.right, distance);
         if (angle < 135 && angle > 45)
         {
             return CollisionSide.Under;
         }
         //The rest of sides by angle
         return CollisionSide.None;
     }
 
 public enum CollisionSide
 {
     Under,
     Above,
     Sides,
     None,
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Bounds.Intersects returns false while collision still works? 1 Answer

How to kill enemy when the bullet hits the BoxColllider2D? 1 Answer

How to keep gameObjects set as triggers to only trigger once, even after a scene reload? 0 Answers

2D Collider Problem 1 Answer

creating an alternative to box collider 2d question 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges