Unity Ray 射线检测

首先在PC端实现鼠标点击某个物体执行某个操作时我们用Input.GetMouseButtonDown(0),获取鼠标点击事件。

再通过Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition)获取鼠标点击屏幕的坐标。

最后判定该坐标是否点击到某个物体:

if(Physics.Raycast(ray,out hit,1000f)

{

if(hit.collider.name=="    ")

  执行对应操作。

}

具体代码如下:

 // 桌面系统鼠标操作
    void DesktopInput()
    {
        if (Input.GetMouseButtonDown(0))
        {


            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 1000f))
            {
                hitname = hit.collider.name;
                if (hitname == "moviePlayerCtl")
                {
                    moviePlayer.gameObject.SetActive(true);
                    maincamer.GetComponent<PosStateRecord>().location("org");
                    goodsShower.gameObject.SetActive(false);
                }
                else if (hitname == "showsOnline")
                {
                    maincamer.GetComponent<PosStateRecord>().location("ui");
                    moviePlayer.gameObject.SetActive(false);
                    goodsShower.gameObject.SetActive(true);
                }
            }
        }
    }

在移动平台操作时,由于没有鼠标,只能用手触屏,所以需要把

if(Input.GetMouseButtonDown(0))改成if(Input.touchCount>0)

触屏坐标的取值方式改成Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position)

移动平台触屏代码如下:

 //移动平台触屏操作
    void MobileInput()
    {
        if (Input.touchCount >0)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position );
            if (Physics.Raycast(ray, out hit, 1000f))
            {
                hitname = hit.collider.name;
                if (hitname == "moviePlayerCtl")
                {
                    moviePlayer.gameObject.SetActive(true);
                    maincamer.GetComponent<PosStateRecord>().location("org");
                    goodsShower.gameObject.SetActive(false);
                }
                else if (hitname == "showsOnline")
                {
                    maincamer.GetComponent<PosStateRecord>().location("ui");
                    moviePlayer.gameObject.SetActive(false);
                    goodsShower.gameObject.SetActive(true);
                }
            }
        }
    }

最后,如果想实现多平台性只需要在Update中检测是哪个平台,再对应调用该平台需要的方法即可:

   void Update()
    {


#if !UNITY_EDITOR && ( UNITY_IOS || UNITY_ANDROID )


       MobileInput(); 
#else
        DesktopInput();
#endif

    }


  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值