I have an orthographic camera that is dynamically sized to give me pinch/zoom effects on a large background map. The camera’s position is also adjusted as you drag the map around.
What I need to do is prevent the camera from moving outside of our predetermined map area. Initially I thought I could just clamp the camera position, but the value that you need to clamp to is dependent on the camera’s current orthographicSize.
So the question is, how can I determine the current “bounding rectangle”(??) for an orthographic camera in world space? At first I thought it was simply the current camera location with the ortho size as an offset on all 4 sides, but that doesn’t seem to be accurate.
Adapted from this answer (and converted to c#), main difference for mine is that extents are moved into update to allow dynamic bounds with pinch and zoom:
Below is the way I solved it in my project. The orthographical camera is set up so that it covers the entire background image at start. I use a reference camera (copy of the camera) that is set to not render anything. I use the reference camera to get unzoomed & unpanned size as well as getting correct focus point depending on view target position.
void LateUpdate()
{
// get camera offset
var offset = (_referenceCamera.WorldToViewportPoint(_cameraFocus.transform.position) - new Vector3(0.5f, 0.5f, 0.0f));
// clamp offset depending on zoom
float clamp = 0.5f - 0.5f / _cameraZoom;
offset = new Vector3(Mathf.Clamp(offset.x, -clamp, clamp), Mathf.Clamp(offset.y, -clamp, clamp), offset.z);
// pan camera
var position = _referenceCamera.transform.position + new Vector3(offset.x * _referenceCamera.orthographicSize * 2.0f * camera.aspect, offset.y * _referenceCamera.orthographicSize * 2.0f, 0f);
camera.transform.position = position;
// zoom camera
camera.orthographicSize = _referenceCamera.orthographicSize / _cameraZoom;
}