Monday, March 14, 2016

c# - How do I make a 2D game resolution independent?


I'm working on a simple 2D game. I've finished the mobile phone version.


However, my boss wants the game to works on his RT. I'm doing the "conversion" but my buttons are in the wrong places, because I hard-coded the screen size, like this:


 texture = game.Content.Load("StartScreen");
mainFrame = new Rectangle(0, 0, game.GraphicsDevice.Viewport.Width, game.GraphicsDevice.Viewport.Height);


// button definitions
startbrect = new Rectangle(300, 258, 88, 88);
startbtext = game.Content.Load("bplay");

In this example, mainframe is fine, but startbrect isn't, because I defined the size to match a Windows phone's screen. How can I handle responsive design when all Windows 8 phones' screens are different? Is there a formula or macro to calculate each time the good size?



Answer



I use a reference screen size, and scale everything according to it, while keeping the ratio of everything the same.


private static float CalcRatio(Vector2 Sizes)
{
return Sizes.y/Sizes.x;

}

public static Vector2 CalculateNewPos(Vector2 RefPos, Vector2 RefScreenSize,
Vector2 CurrentScreenSize)
{
return new Vector2((RefPos.x/RefScreenSize.x) * CurrentScreenSize.x,
(RefPos.y/RefScreenSize.y) * CurrentScreenSize.y);
}

public static Vector2 CalculateNewSize(Vector2 RefSize, Vector2 RefScreenSize,

Vector2 CurrentScreenSize)
{
float origRatio = CalcRatio(RefSize);
float perW = RefSize.x * 100f / RefScreenSize.x;
float newW = perW / 100f * CurrentScreenSize.x;
float newH = newW * origRatio;
return new Vector2(newW, newH);
}

To make sure the game looks good on resolutions with ratios substantially different from your reference resolution's, define a "playable area", that fits into any kind of screen, and put all of the gameplay critical visuals there. Fill everything outside of it with background. Usually, my reference playable area is as big as the reference screen size itself.



On portrait orientations, I calculate the (new) playable area so that the screen is filled vertically, and the space it takes horizontally is just as big as it is required to keep the ratio. On landscape orientations, I fill the screen horizontally, and keep the ratio when setting the vertical size.


For more, see http://en.wikipedia.org/wiki/Safe_area_(television) as it's a similar, if not identical, concept.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...