- Home /
Targeting multiple display resolution in 2D games
I am trying to create 2D game in Unity but I want to consider wide variety of android devices for this. But I found that game area is cropped differently per resolution change.
Also I already run demo 2D Platformer game in different devices but I found same situation in this game also.
So how to handle this situation in Unity 2D game development?
The way I do it (for GUI, I'm not sure if 2D is the same) is by using percentages of the screen. If 800 is x percent of resolution that I'm using to develop, then use that percent to calculate for different aspect ratios. Then you can handle most aspect ratios!
Thanks for your reply but you put it as answer not create so much long comment so that we discuss this thing more and I can give you a point.
Answer by siddharth3322 · Jan 16, 2014 at 02:23 PM
I got my thing worked by using following code snippets. I pasted it for helping other members.
public class ControllingCameraAspectScript : MonoBehaviour
{
// Use this for initialization
void Start()
{
// set the desired aspect ratio (the values in this example are
// hard-coded for 16:9, but you could make them into public
// variables instead so you can set them at design time)
float targetaspect = 16.0f / 9.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;
}
}
}
Still exist black bars in some resolution. So how to remove that black bars? This works great in pc but in mobile devices have no effect.
This is a bit unrelated, but I'm still fresh to C# and I have a small doubt about that code you posted.
This line: float windowaspect = (float)Screen.width / (float)Screen.height;
wouldn't it be exactly the same as: float windowaspect = Screen.width / Screen.height;
I don't understand the purpose of those float within parentheses...
Completely off-topic, @Tricephalus... Screen.width
is an integer, Screen.height
is an integer. Divide an integer by an integer and what do you get?
If you said "the wrong answer", score 10 points. That's what you (cast) them as floats first.
Got it! Thank you
I don't know why, but I assumed that without casting them as floats, since you had cast the variable as being a float, the operation would return a float.
Live and learn :)