Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

click or touch event for Box Collider 2D

Discussion in '2D' started by jbassking, Mar 19, 2014.

  1. jbassking

    jbassking

    Joined:
    Feb 27, 2014
    Posts:
    106
    I have a Box Collider 2D and need to know when the user clicks or touches (for touch screen) the object. I tried adding OnMouseDown but this doesn't always seem to get triggered.
    I also tried to use the Raycast but that doesn't seem to always work either.

    I haven't found anything that seems consistent yet.

    Here's what I tried for touch:
    if (Input.GetMouseButtonDown (0)) {
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

    RaycastHit hit;
    // Casts the ray and get the first game object hit
    if (Physics.Raycast (ray, out hit))
    OnMouseClick ();
    //Debug.Log(hit.transform.gameObject);
    }

    if (Input.touchCount == 1)
    {
    Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
    Vector2 touchPos = new Vector2(wp.x, wp.y);
    if (collider2D == Physics2D.OverlapPoint(touchPos))
    {
    OnMouseClick();

    }
    }

    Thanks.
     
  2. Kurius

    Kurius

    Joined:
    Sep 29, 2013
    Posts:
    412
  3. Dumanarif

    Dumanarif

    Joined:
    Dec 2, 2015
    Posts:
    2