# Calculating Camera Boundary to Prevent Drawing 'Outside' the Level

Hi all! I’m having some trouble, probably relating to a limited knowledge of math, limiting my camera’s position so that it doesn’t draw anything beyond the boundaries of the level.

Problem:

I am creating a 2.5D platformer. I have a Zone gameobject which contains various properties for a given area of a level. Each Zone has a Rect field which defines the gameplay limits of the Zone (xmin, xmax, ymin, ymax) outside which no gameplay or art will exist. The camera, which uses perspective projection, is situated at a variable z distance from the gameplay axis. I would like to limit the camera’s movement so that the visible area does not exceed xmin, xmax, ymin or ymax on the zero-z-axis.

I’m not great with math, unfortunately, but I thought I might be able to solve the problem by calculating the visible rectangle where z = zero, and then correcting position where that visible rectangle exceeds the boundary of the Zone… but I’m only guessing and I’ve had no luck anyway calculating that visible rectangle.

Perhaps there’s an easier way to solve this problem, with clever use of game objects or colliders? I’m really stumped on this one.

I’ve solved the issue (and introduced a new one). To block the camera within the zone’s boundary, I calculate the visible rectangle on z = zero with this:

``````Vector3 bottomLeft = camera.ScreenToWorldPoint(new Vector3(0.0f, 0.0f, -transform.position.z));
Vector3 topRight = camera.ScreenToWorldPoint(new Vector3(camera.pixelWidth, camera.pixelHeight, -transform.position.z));
m_viewPlane = new Rect(bottomLeft.x, bottomLeft.y, topRight.x - bottomLeft.x, topRight.y - bottomLeft.y);
``````

And then correct the position:

``````x = Mathf.Clamp(x, m_zone.Boundary.xMin + ViewPlaneHalfWidth, m_zone.Boundary.xMax - ViewPlaneHalfWidth);
y = Mathf.Clamp(y, m_zone.Boundary.yMin + ViewPlaneHalfHeight, m_zone.Boundary.yMax - ViewPlaneHalfHeight);
``````

Now I’m trying to solve a more complicated issue. When the zone width is narrower than the viewing plane width, I’d like to move the camera towards zero in z-axis to reduce the size of the viewing plane until it fits. Basically, zoom in when we’re in enclosed spaces.

I’ll keep trying to solve it myself and post if I succeed, but again if someone has an idea I’d love to hear it.