// assuming the ground is on it's own layer called 'ground-plane'
int mask = 1 << LayerMask.NameToLayer("ground-plane");
// get the 2 camera-corner rays
Ray topRightRay = Camera.main.ViewportPointToRay(Vector3.zero);
Ray bottomLeftRay = Camera.main.ViewportPointToRay(Vector3.one);
// find the corners of the terrain-rect
RaycastHit topRightRH;
RaycastHit bottomLeftRH;
Rect result;
if( Physics.Raycast(topRightRay, out topRightRH, Mathf.Infinity, mask) && Physics.Raycast(bottomLeftRay , out bottomLeftRH, Mathf.Infinity, mask) )
{
result = Rect.MinMaxRect(topRightRH.point.x, topRightRH.point.y, bottomLeftRH.point.x, bottomLeftRH.point.y);
}
else
{
throw new InvalidOperationException("Cannot get the terrain rect when the camera isn't completely over the terrain");
}
return result;
↧