- Home /
Keeping an object in camera view in multiple screen resolutions?
I am making an arcade shooter, and I want the player to always be in a certain area. At one screen resolution, the player maxes out at 14 and -14 for left and right, but in another resolution it's 12 and -12. How can I keep the player in the camera area even though the max values change on different screen resolutions? I program in C# normal so I'd prefer C# code if possible, but I can do JavaScript if need be.
Answer by Tomer-Barkan · Nov 19, 2013 at 06:55 PM
The way it works, is that the camera "size" that you set (field of view for perspective, size for orthographic), defines the distance from top to bottom. But then, when the aspect ratio changes (as in 4:3, 16:9, 16:10, etc - this is not the same as resolution), the height of your camera's view remains the same, but since the ratio between height and width changed due to the new aspect ratio, the width of the camera view must change as well.
So say the height is 30 game units, and the aspect ratio is 4:3 (say 800x600) - then the width is 4/3 times the height, so the width is 40.
Now if you change the aspect ratio to 16:9 (say 1920x1080) - then the width will be 16/9 times the height = around 53.
You see, now in the widescreen aspect ratio, you will see more to the sides.
How exactly you handle this, is up to you. You can decide you always plan for the lowest aspect ratio (5:4) - then you design the game using this aspect ratio, and any other resolution will have MORE to the sides, instead of left. So you don't have to be afraid of parts of the game being cut out.
A better but harder way to deal with this would be to plan a different camera view for each of the common resolutions. This requires for you to design more than one GUI, and then set the camera's values and the GameObject's locations according to the resolution.
If you are an indie developer with limited resources I recommend going for a constant view. Plan for 5:4 aspect ratio, and if someone has a wider screen they will get more in the sides, but everything that you plan to be in the screen will always be in the screen.
Answer by Sparrowfc · Nov 19, 2013 at 04:07 PM
Usually I made a static class to handle resolution adaption. I'm assuming you talking about a 2D UI object but not a 3D object. Hopes that may help
public class ResAdaptor
{
static float readonly originWidth = 1024;
static float readonly originHeight = 768;
static float xRate = 0;
static float yRate = 0;
public static float XRate
{
get
{
if(xRate == 0)
xRate = Screen.width / originWidth;
return xRate;
}
}
public static float YRate
{
get
{
if(yRate == 0)
yRate = Screen.height/ originHeight;
return yRate;
}
}
public static Vector2 AVector2(float x, float y)
{
return new Vector2(x * XRate, y * YRate);
}
public static Rect ARect(float x, float y, float width, float height)
{
return new Rect(x * XRate, y * YRate, width * XRate, height * YRate);
}
}