Unity-判断物体是否在相机视野内

public static bool IsGameObjectInCameraView(GameObject targetObj, Camera camera = null)
{
if (camera == null)
camera = Camera.main;

if (camera == null)
return false;

Vector3 targetObjViewportCoord = camera.WorldToViewportPoint(targetObj.transform.position);
if (targetObjViewportCoord.x > 0 && targetObjViewportCoord.x < 1 && targetObjViewportCoord.y > 0f && targetObjViewportCoord.y < 1 && targetObjViewportCoord.z > camera.nearClipPlane && targetObjViewportCoord.z < camera.farClipPlane)
return true;

return false;
}

你可能感兴趣的:(Unity3D)