2Dゲームを作っている時に色んなデバイスで画面サイズを背景に合わせたい時があったのでメモ。
- 背景にサイズを合わせたい
- アスペクト比は固定にしたい
- 背景からはみ出す部分は黒くしたい
- デバイスのスクリーンサイズから縦に合わせるか横に合わせるかを判断してアスペクト比を固定で表示させたい
今回使用する画像
これのアスペクト比を保ったまま表示させたいです。
640×960 の縦長の画像
配置
縦にフィットさせる
画面サイズを画像の縦サイズにフィットさせるスクリプトを用意してカメラにアタッチします。
カメラのorthographicSizeがカメラの縦幅の半分なので、そこに画像サイズをpixle per unitで割った値を入れます。
StableAspect.cs
private Camera cam;
// 画像のサイズ
private float width = 640f;
private float height = 960f;
// 画像のPixel Per Unit
private float pixelPerUnit = 100f;
void Awake () {
// カメラコンポーネントを取得します
cam = GetComponent<Camera> ();
// カメラのorthographicSizeを設定
cam.orthographicSize = height / 2f / pixelPerUnit;
}
横の余白を切り取る
まだ両サイドの余白が丸見えなので、これをマスクする形で隠します。
Cameraのviewport rectが画面内のどこに描画されるかを設定するプロパティなので、それを設定します。
それにしてもinspector上のプロパティ名とスクリプトで名前が違うのはなんでなのでしょうか。
StableAspect.cs
private Camera cam;
// 画像のサイズ
private float width = 640f;
private float height = 960f;
// 画像のPixel Per Unit
private float pixelPerUnit = 100f;
void Awake () {
// カメラコンポーネントを取得します
cam = GetComponent<Camera> ();
// カメラのorthographicSizeを設定
cam.orthographicSize = height / 2f / pixelPerUnit;
// 縦幅の倍率
float bgScale = height / Screen.height;
// viewport rectの幅
float camWidth = width / (Screen.width * bgScale);
// viewportRectを設定
cam.rect = new Rect ((1f - camWidth) / 2f, 0f, camWidth, 1f);
}
このviewport rectが結構曲者で、0から1の値に正規化されています。
横幅を合わせるだけなので、width / Screen.widthでフィットしそうな気がするんですが、それではだめです。
画像の縦幅が画面サイズに合わせてスケールしているため、そのスケールの割合を加味する必要があります。
それがbgScaleです。
縦だけでなく横にもフィットさせる
横方向も加味します。
StableAspect.as
private Camera cam;
// 画像のサイズ
private float width = 640f;
private float height = 960f;
// 画像のPixel Per Unit
private float pixelPerUnit = 100f;
void Awake () {
float aspect = (float)Screen.height / (float)Screen.width;
float bgAcpect = height / width;
// カメラコンポーネントを取得します
cam = GetComponent<Camera> ();
// カメラのorthographicSizeを設定
cam.orthographicSize = (height / 2f / pixelPerUnit);
if (bgAcpect > aspect) {
// 倍率
float bgScale = height / Screen.height;
// viewport rectの幅
float camWidth = width / (Screen.width * bgScale);
// viewportRectを設定
cam.rect = new Rect ((1f - camWidth) / 2f, 0f, camWidth, 1f);
} else {
// 倍率
float bgScale = width / Screen.width;
// viewport rectの幅
float camHeight = height / (Screen.height * bgScale);
// viewportRectを設定
cam.rect = new Rect (0f, (1f - camHeight) / 2f, 1f, camHeight);
}
}
![スクリーンショット 2015-07-25 10.44.38.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.amazonaws.com%2F0%2F29966%2F5bda6df8-e3c4-dd4d-246f-0cae12ffd34d.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=6504b9f71d72fdba37d7e81225555f2a)