0

I have an object hit that contains a Polygon Collider, and in this object I have some objects that contain BoxCollider. Now I'm trying to detect when I click Polygon Collider, and when I click Box Collider. So when I click Box Collider, you should avoid the Polygon Collider.

if (Input.GetMouseButtonDown(0))
{
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit))

       if (hit.collider.GetType() != typeof(BoxCollider2D))
       {
            Debug.Log("Bad Click");
       }
       else
            Debug.Log("Good Click");
}

So I can not find any way to help me. If anyone has any idea, thank you!!!

Jonas
  • 1,473
  • 2
  • 13
  • 28
George
  • 45
  • 7
  • so when you click the Box collider the collision is detected for both box and the polygon? – Milad Qasemi May 31 '18 at 08:47
  • yes....but I would like to initially detect the box collider , and if it is to avoid the polygon collider – George May 31 '18 at 09:07
  • 1
    so in your code, you just can say if both of them got detected then only call the method for when only the box collider is detected. – Milad Qasemi May 31 '18 at 09:10

1 Answers1

0

This shouldn't work at-all because RaycastHit and Physics.Raycast are used for 3D colliders. For 2D colliders, RaycastHit2D and Physics2D.Raycast should be used. Also, for checking if the object has BoxCollider2D or PolygonCollider2D attached to it, the GetComponent function is used instead of hit.collider.GetType(). It returns null when the component is not available.

Your raycast code should look like something below:

if (Input.GetMouseButtonDown(0))
{
    Camera cam = Camera.main;

    Vector2 wPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast(wPoint, Vector2.zero);

    //Check if we hit anything
    if (hit)
    {
        if (hit.collider.GetComponent<BoxCollider2D>() != null)
        {
            Debug.Log("Bad Click");
        }
        else if (hit.collider.GetComponent<PolygonCollider2D>() != null)
            Debug.Log("Good Click");
    }
}

That should fix your problem but I suggest you use the new Event System with OnPointerClick. See #7 from my other answer on how to use it with a 2D collider.

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • yes, it works, but it has bugs, many times when need to debug good click, I get a bad click – George Jun 05 '18 at 12:31
  • I solved the problem by changing the position of z. We have changed to objects containing the Box Collider 2D Z position ahead. – George Jun 05 '18 at 13:11