How to maintain width at lower aspect ratios?
In a 2D game, when switching from a higher aspect ratio to a lower one (for example, from 16:9 to 4:3), the width of the viewing window shrinks, causing elements near the sides to get "cut off." Is there an easy way (perhaps a setting, script, or component) to add height instead of subtracting width when changing to a lower aspect ratio? In other words, instead of things near the sides getting hidden, more things near the top and bottom would be revealed.
I'm guessing this would involve zooming the camera out just enough so that whatever was at the left and right edge at the larger aspect ratio would still be at the edges at the lower one. Does anyone know if this has been done before? For the particular game I'm making, zooming the camera out to reveal more of the scene would be preferable to cutting off the edges. But if possible, I only want to zoom out if necessary.
Answer by inejwstine · Sep 26, 2018 at 05:36 PM
I think I just found a workable solution for me. I'm sharing it in case it's helpful to anyone else. I wrote this very simple script and attached it to my Main Camera:
public class AdjustToAspectRatio : MonoBehaviour {
[SerializeField] private float _16By9CameraSize;
[SerializeField] private float _4By3CameraSize;
private const float RATIO_16_9 = 16f / 9f;
private const float RATIO_4_3 = 4f / 3f;
private float _aspectRatio;
private Camera _camera;
// Use this for initialization
void Start () {
_camera = GetComponent<Camera>();
_aspectRatio = (float)Screen.width / Screen.height;
var t = (_aspectRatio - RATIO_4_3) / (RATIO_16_9 - RATIO_4_3);
var size = Mathf.Lerp(_4By3CameraSize, _16By9CameraSize, t);
_camera.orthographicSize = size;
}
}
I'm expecting the aspect ratio of the devices that will be playing my game to be somewhere between 16:9 and 4:3. So I checked both ratios in the editor Game view and adjusted the camera's orthographic size (just "Size" in the inspector) at each ratio so it looked how I wanted and then entered those values into the corresponding fields.
Now when I play at 16:9, it sets the camera size to _16By9CameraSize. When I play at 4:3, it sets it to _4By3CameraSize. And when I play at an aspect ratio that's somewhere between the two (say, 3:2), this script will interpolate between the two values.
There may be a more elegant solution, but for now, this suits my needs. Feel free to use it or improve upon it. (If you do improve it, I'd love to hear how!)
Your answer
Follow this Question
Related Questions
How can I scale a scrollview item so it keeps its ratio? 0 Answers
Designed UI for 2:1 aspect raito, how do I also make it fit 16:9? 1 Answer
Resizable Window with Fixed Aspect Ratio? 2 Answers
Unity built game resolution issue 1 Answer
Camera and UI settings for aspect ratio independent 2D game 1 Answer