Reputation: 47
I am working on 2D android game in unity (portrait view). I am using following code to scale my game scene to fit all screens and it worked with all mobiles
void Start()
{
float targetaspect = 9.0f / 16.0f;
// determine the game window's current aspect ratio
float windowaspect = (float)Screen.width / (float)Screen.height;
// current viewport height should be scaled by this amount
float scaleheight = windowaspect / targetaspect;
// obtain camera component so we can modify its viewport
Camera camera = GetComponent<Camera>();
// if scaled height is less than current height, add letterbox
if (scaleheight < 1.0f)
{
Rect rect = camera.rect;
rect.width = 1.0f;
rect.height = scaleheight;
rect.x = 0;
rect.y = (1.0f - scaleheight) / 2.0f;
camera.rect = rect;
}
else // add pillarbox
{
float scalewidth = 1.0f / scaleheight;
Rect rect = camera.rect;
rect.width = scalewidth;
rect.height = 1.0f;
rect.x = (1.0f - scalewidth) / 2.0f;
rect.y = 0;
camera.rect = rect;
}
}
But when I tested my game on tablet it fit perfectly in height but in case of width, game view width was shorter than the tablet screen width. There was a black area seen on both sides of tablets.
Note: according to the above code, game view get scaled to the size 480X854.
Thank you for showing interest in my query!!!
Upvotes: 0
Views: 1632
Reputation: 1161
That's exactly what your code says it's doing. See the "add pillarbox" comment. This script is ensuring you always see 9:16 aspect ratio by adding empty space where the device isn't 9:16.
You likely haven't seen a problem on phones because so many smartphones use the 16:9 aspect ratio (9:16 portrait) which exactly matches the base aspect ratio in this script. Many tables are more squared (4:3 for iPad) so tablets are more likely to show boxing. Devices wider than 16:9 will show letterboxing.
If you don't want the letterboxing and pilarboxing effect then don't use this script!
Design your game UI so it doesn't depend on a single aspect ratio. Unity UI has built in support for this. See CanvasScaler and the flexible layout options provided by RectTransform for example.
Upvotes: 1