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

前端 未结 1 959
醉梦人生
醉梦人生 2021-01-07 15:30

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()
{
    Deb         


        
相关标签:
1条回答
  • 2021-01-07 16:37

    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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题