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<.NameToLayer ("layername")))
        {
            Debug.Log("检测到物体");
        }

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

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

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

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

你可能感兴趣的:(基础)