本文介绍了使用Physics.Raycast和Physics2D.Raycast检测对对象的点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的场景中有一个空的游戏对象,带有一个2D零件盒对撞机.

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 ?

推荐答案

使用射线投射.检查是否按下了鼠标左键.如果是这样,请从发生鼠标单击的位置到发生碰撞的位置发出不可见的光线.对于3D对象,请使用:

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模型:

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:

以上解决方案适用于3D.如果您希望它适用于2D,则将 Physics.Raycast 替换为 Physics2D.Raycast .例如:

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

这篇关于使用Physics.Raycast和Physics2D.Raycast检测对对象的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 20:46