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

瘦欲@ 提交于 2019-11-30 20:58:41

问题


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 ?


回答1:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/30291233/detect-clicks-on-object-with-physics-raycast-and-physics2d-raycast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!