Unity射线检测整理

Unity射线检测常见的几种应用

一:检测单个物体

//初始化射线:中心+方向
        Ray rayNoraml = new Ray(Vector3.zero,Vector3.up*10);
        //绘制射线
        Debug.DrawRay(transform.position,transform.forward,Color.red,10);

        if (Input.GetMouseButtonDown(0))
        {
            //射线检测:从屏幕中心发出一条射线
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            //15+种重载:射线,碰撞 ,射程,开启的层级
            if (Physics.Raycast(ray,out hit,1000,1 << LayerMask.NameToLayer("Enemy")))
            {
                Debug.Log(hit.collider.name);

               Debug.Log(hit.point);
                if (hit.collider.tag == "Enemy")
                {

                }
            }

        }

 

二:检测多个物体

        只要存在Collider,满足方法参数对应的条件,都可以使用射线检测碰撞。

if (Input.GetMouseButtonDown(0))
 {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay(ray.origin, ray.direction, Color.red);
            RaycastHit[] hit = Physics.RaycastAll(ray, Mathf.Infinity,1 << LayerMask.NameToLayer("Enemy"));
            if (hit.Length > 0)
            {
                for (int i = 0; i < hit.Length; i++)
                {
                    Debug.Log("检测到物体" + hit[i].collider.name);
                }
            }
 }

 

三:球形检测

if (Input.GetMouseButtonDown(0)){

        int radius = 10;
        Collider[] cols = Physics.OverlapSphere(this.transform.position, radius, LayerMask.NameToLayer("Enemy"));
        if(cols.Length >0)
        {
            for (int i = 0; i < cols.Length; i++)
            {
                Debug.Log("检测到物体" + cols[i].name);
            }
        }

}

  

 private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(this.transform.position, 10);
    }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值