该方法适用于3D Canvas, 和 2D且赋值了相机的Canvas。 不适合2D没有赋值相机的Canvas。
/// <summary>
/// 判断ui是否能被cam可见
/// </summary>
public bool GetUIVisable(Camera cam, RectTransform ui)
{
bool value = true;
Vector3 pos = cam.WorldToScreenPoint(ui.position);
if (pos.z < 0 || pos.x < 0 || pos.x > Screen.width || pos.y < 0 || pos.y > Screen.height)
value = false;
return value;
}
public bool GetObjCenterVisable(Camera cam, Transform obj)
{
//转化为视角坐标
Vector3 viewPos = cam.WorldToViewportPoint(obj.position);
// z<0代表在相机背后
if (viewPos.z < 0)
return false;
// 距离farClipPlane太远,摄像机看不到了
if (viewPos.z > cam.farClipPlane)
return false;
// x,y取值在 0~1之外时代表在视角范围外
if (viewPos.x < 0 || viewPos.y < 0 || viewPos.x > 1 || viewPos.y > 1)
return false;
return true;
}
在范围内,即可见。
/// <summary>
/// 相机包围盒
/// </summary>
private Plane[] _mTempCameraPlanes = new Plane[6];
private void Update()
{
//使用方法;
print(GetBondsVisable(transform.position, GetComponent<BoxCollider>().size));
}
private void LateUpdate()
{
//调用Unity的API,获取相机包围盒
GeometryUtility.CalculateFrustumPlanes(Camera.main, _mTempCameraPlanes);
}
/// <summary>
/// 通过相机包围盒来判定物体是否在视野中。
/// </summary>
public bool GetBondsVisable(Vector3 center, Vector3 size)
{
Bounds bound = new Bounds(center, size); //这里的Size是半径
return GeometryUtility.TestPlanesAABB(_mTempCameraPlanes, bound);
}
大家还有什么问题,欢迎在下方留言!