Reputation: 63
Say I have a GameObject
inside a 2D scene and a camera. And I want to change the size and position of the camera so that even when the screen resolution changes, the object will still be visible. So, how can I do that?
Upvotes: 1
Views: 4735
Reputation: 63
TL;DR: Scroll down to the bottom for the code.
First up, we must set the position of the camera to the middle of the object so the scaling of the camera would be easier.
Second, to scale the camera, we're going to change the orthographicSize
of the camera in our script (Which is the Size
attribute in the Camera
component). But how do we calculate the attribute?
Basically, the Size
attribute here is half the height of the camera
. So, for example, if we set the Size
to 5
, that mean the height of camera going to be 10 Unity Unit (which is something I made up so you can understand easier)
.
So, it seems like we just have to get the height of the object, divide it by 2 and set the Size
of the camera to the result, right? (1)
Well, not really. You see, while it might work on certain cases, when the width of the object is way, way longer than the screen, and the height if way, way shorter, then the camera would not able to see all of the object.
But why is that? Now, let's say that our camera has a width/height of 16/9, and our object is 100/18. That means if we scale using the height, our camera's width/height would be 32/18, and while it's enough to cover the height, it isn't enough to cover the width. So, another approach is to calculate using the width
By taking the width of the object, divide it by the width of the camera and then multiply with the height of the camera (then of course, divide by 2). We would be able to fit the whole width of the object. (Because of... ratio or something) (2)
BUT AGAIN, it has the same problem as our first approach, but the object being too tall instead too wide.
So, to solve this, we just have to place a check if the first approach (see (1))
if the object is being overflowed, and if it is, then we just use the second approach instead (see (2))
. And that's it
And here's the code btw:
// replace the `cam` variable with your camera.
float w = <the_width_of_object>;
float h = <the_height_of_object>;
float x = w * 0.5f - 0.5f;
float y = h * 0.5f - 0.5f;
cam.transform.position = new Vector3(x, y, -10f);
cam.orthographicSize = ((w > h * cam.aspect) ? (float)w / (float)cam.pixelWidth * cam.pixelHeight : h) / 2;
// to add padding, just plus the result of the `orthographicSize` calculation with number, like this:
// | |
// V V
// ... cam.pixelHeight : h) / 2 + 1
Upvotes: 3