- Home /
Question by
JoshDangIt · Sep 11, 2018 at 03:40 PM ·
zoombounds2d camera
Calculating 2D Camera Bounds With Zoom
I'm making a 2D game where the player has full control over the position of the camera (holding right click and dragging the screen) and the zoom of the camera (Scroll wheel). What I've been trying to do is clamp the camera's position and zoom so that the player can only see what's inbounds. I've seen other people answer questions on how to clamp a 2D camera's position. (Like this one) None of them help with figuring out how to clamp the zoom though.
Here's My code so far:
void Update ()
{
Vector3 move = Vector3.zero;
float newSize = cam.orthographicSize;
if (CanMove ())
{
if (Input.GetMouseButtonDown(1))
{
dragOrigin = Input.mousePosition;
}
else if (Input.GetMouseButton(1))
{
Vector3 pos = cam.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
move = new Vector3(pos.x * dragSpeed, pos.y * dragSpeed, 0) * -1f;
dragOrigin = Input.mousePosition;
}
}
if (CanZoom ())
{
float z = Input.GetAxis ("Mouse ScrollWheel");
z *= -1f;
if (Input.GetKeyDown (KeyCode.Space))
print (z);
newSize += z * zoomSpeed * Time.deltaTime;
}
//TODO clamp camera
transform.Translate(move);
cam.orthographicSize = newSize;
}
Comment