Clément Andraud
Clément Andraud

Reputation: 9269

Detect clicks on Object with Physics.Raycast and Physics2D.Raycast

I have an empty gameobject on my scene with a component box collider 2D.

I attached a script to this game object with :

void OnMouseDown()
{
    Debug.Log("clic");
}

But when i click on my gameobject, there is no effect. Do you have any ideas ? How can i detect the click on my box collider ?

Upvotes: 0

Views: 6413

Answers (1)

Programmer
Programmer

Reputation: 125245

Use ray cast. Check if left mouse button is pressed. If so, throw invisible ray from where the mouse click occurred to where to where the collision occurred. For 3D Object, use:

3D Model:

void check3DObjectClicked ()
{
    if (Input.GetMouseButtonDown (0)) {
        Debug.Log ("Mouse is pressed down");
    
        RaycastHit hitInfo = new RaycastHit ();
        if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo)) {
            Debug.Log ("Object Hit is " + hitInfo.collider.gameObject.name);

            //If you want it to only detect some certain game object it hits, you can do that here
            if (hitInfo.collider.gameObject.CompareTag ("Dog")) {
                Debug.Log ("Dog hit");
                //do something to dog here
            } else if (hitInfo.collider.gameObject.CompareTag ("Cat")) {
                Debug.Log ("Cat hit");
                //do something to cat here
            }
        } 
    } 
}

2D Sprite:

The solution above would work for 3D. If you want it to work for 2D, replace Physics.Raycast with Physics2D.Raycast. For example:

void check2DObjectClicked()
{
    if (Input.GetMouseButtonDown(0))
    {
        Debug.Log("Mouse is pressed down");
        Camera cam = Camera.main;

        //Raycast depends on camera projection mode
        Vector2 origin = Vector2.zero;
        Vector2 dir = Vector2.zero;

        if (cam.orthographic)
        {
            origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        }
        else
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            origin = ray.origin;
            dir = ray.direction;
        }

        RaycastHit2D hit = Physics2D.Raycast(origin, dir);

        //Check if we hit anything
        if (hit)
        {
            Debug.Log("We hit " + hit.collider.name);
        }
    }
}

Upvotes: 4

Related Questions