当前位置:   article > 正文

Unity 常用射线检测方法_unity射线检测

unity射线检测

1.普通射线检测(一般用于检测某一个物体)

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Debug.DrawRay(ray.origin ,ray.direction , Color.red);
        RaycastHit hit;
        if(Physics .Raycast (ray,out hit,int.MaxValue,1<<LayerMask .NameToLayer ("layername")))
        {
            Debug.Log("检测到物体");
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.直线射线检测多个物体

  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("layername"));
        if(hit .Length >0)
        {
            for (int i = 0; i < hit.Length ; i++)
            {
                Debug.Log("检测到物体"+hit[i].collider.name );
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.球形射线检测(一般用于检测周边物体)

   int radius = 3;
        Collider[] cols = Physics.OverlapSphere(this.transform.position, radius, LayerMask.NameToLayer("layername"));
        if(cols.Length >0)
        {
            for (int i = 0; i < cols.Length; i++)
            {
                Debug.Log("检测到物体" + cols[i].name);
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

画出球形检测范围方法,可用

private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(this.transform.position, 3);
    }
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/98304
推荐阅读
相关标签
  

闽ICP备14008679号