Unity 2D - Scale/Resize Camera Based On Screen Resolution/Size

Unity 2D - Scale/Resize Camera Based On Screen Resolution/Size

If you are building a 2D game for devices with various screen sizes, the first thing you would need is to have the look and feel of your game, same across all the devices. To achieve this you would want to change the size of your Orthographic camera based on the screen height.

In short, this post lets you create a script which will help you resize the camera based on the screen size of the device the game is being played on.

Create a new C# script named ScalableCamera and attach it to the Main Camera in your scene. Open the script and add the below code to it:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ScalableCamera : MonoBehaviour {
 
 // Use this for initialization
 void Start () {
  float TARGET_WIDTH = 960.0f;
  float TARGET_HEIGHT = 540.0f;
  int PIXELS_TO_UNITS = 30; // 1:1 ratio of pixels to units
  
  float desiredRatio = TARGET_WIDTH / TARGET_HEIGHT;
  float currentRatio = (float)Screen.width/(float)Screen.height;
  
  if(currentRatio >= desiredRatio)
  {
   // Our resolution has plenty of width, so we just need to use the height to determine the camera size
   Camera.main.orthographicSize = TARGET_HEIGHT / 4 / PIXELS_TO_UNITS;
  }
  else
  {
   // Our camera needs to zoom out further than just fitting in the height of the image.
   // Determine how much bigger it needs to be, then apply that to our original algorithm.
   float differenceInSize = desiredRatio / currentRatio;
   Camera.main.orthographicSize = TARGET_HEIGHT / 4 / PIXELS_TO_UNITS * differenceInSize;
  }
 }
}


Save the script and return to unity and test the scene. Vary the PIXEL_TO_UNITS variable value to get the desired screen size based on your sprites' PixelToUnits value. Make sure you stop the scene and then change the resolution for the code to update the Camera size as our code is in the Start method.

Unity 2D - Scale/Resize Camera Based On Screen Resolution/Size


See you around
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

2 comments:

  1. Such a nice content. one can also get information on camera from infoshutter

    ReplyDelete
  2. In Camera.main.orthographicSize = TARGET_HEIGHT / 4 / PIXELS_TO_UNITS;
    why do you divide by 4 and not by 2?

    ReplyDelete