射线检测单个游戏对象
//射线检测一个游戏对象
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
bool isRaycast = Physics.Raycast(ray, out hit);
if (isRaycast)
{
Debug.DrawLine(ray.origin, hit.point, Color.green);
print("坐标" + hit.transform.position);
print("碰撞到点的坐标" + hit.point);
print("重心坐标" + hit.barycentricCoordinate);
print("碰撞盒" + hit.collider);
print("距离" + hit.distance);
print("光线地图坐标" + hit.lightmapCoord);
print("法线" + hit.normal);
print("刚体" + hit.rigidbody);
print("纹理坐标" + hit.textureCoord);
print("三角指数" + hit.triangleIndex);//等等
}
直线射线检测多个物体
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 );
}
}
球形射线检测(一般用于检测周边物体)
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);
}
来源:CSDN
作者:Unity刘文凯
链接:https://blog.csdn.net/LWKlwk11/article/details/104018487