首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Physics.Raycast和Physics2D.Raycast检测对对象的单击

使用Physics.Raycast和Physics2D.Raycast检测对对象的单击
EN

Stack Overflow用户
提问于 2015-05-17 19:30:38
回答 1查看 5.8K关注 0票数 0

我有一个空的游戏对象在我的场景与组件盒对撞机2D。

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

代码语言:javascript
运行
复制
void OnMouseDown()
{
    Debug.Log("clic");
}

但是当我点击我的游戏对象时,就没有效果了。你有什么想法吗?如何检测到对我的盒对撞机的点击?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-17 21:53:53

用射线投射。检查鼠标左键是否按下。如果是,则从鼠标单击发生的位置向发生碰撞的位置抛出不可见的射线。对于3D对象,请使用:

三维模型:

代码语言:javascript
运行
复制
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雪碧:

以上解决方案适用于3D。如果您想让它在2D上工作,请将Physics.Raycast替换为Physics2D.Raycast.例如:

代码语言:javascript
运行
复制
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);
        }
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30291233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档