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
- 67
- 8
- 9
画出球形检测范围方法,可用
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(this.transform.position, 3);
}
- 2
- 3
- 4