检测点击对象与物理.光线投射和物理2d

本文关键字:光线投射 2d 对象 检测 | 更新日期: 2023-09-27 17:49:38

我的场景中有一个空的gameobject和一个组件盒碰撞器2D。

我给这个游戏对象附加了一个脚本:

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

但是当我点击我的游戏对象时,没有效果。你有什么主意吗?我如何检测点击我的框碰撞器

检测点击对象与物理.光线投射和物理2d

使用光线投射。检查是否按下鼠标左键。如果是,则从鼠标点击发生的地方向发生碰撞的地方投掷不可见射线。对于3D对象,使用:

3 d模型:

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

2 d雪碧:

上述解决方案适用于3D。如果你想让它在2D中工作,替换Physics。使用Physics2D.Raycast。例如:

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