ユーザ用ツール

サイト用ツール

wiki:unity:tips:051

差分

この文書の現在のバージョンと選択したバージョンの差分を表示します。

この比較画面にリンクする

次のリビジョン
前のリビジョン
wiki:unity:tips:051 [2014/11/13 07:46]
127.0.0.1 外部編集
wiki:unity:tips:051 [2015/02/23 12:45] (現在)
ライン 1: ライン 1:
-====== 051 Spriteの画面解像度対応 ====== +[[http://stepism.sakura.ne.jp/unity/wiki/|Unityはちら移動しまし]]
- +
-===== 概要 ===== +
-Spriteのサイズや位置を画面解像度に合わせて調整します。 +
- +
-==== ソースコード ==== +
-<code csharp>​ +
-using UnityEngine;​ +
-using System.Collections;​ +
- +
-public class CameraScript ​MonoBehaviour +
-+
- public const float PixelToUnits = 100.0f; +
-  +
- // ゲーム内解像度 +
- public const int BaseScreenWidth = 640; +
- public const int BaseScreenHeight = 960; +
-  +
- void Awake() +
-+
- Camera cam = gameObject.GetComponent<​Camera>​();​ +
- cam.orthographicSize = BaseScreenHeight / PixelToUnits / 2; +
-  +
- float baseAspect = (float)BaseScreenHeight / (float)BaseScreenWidth;​ +
- float nowAspect = (float)Screen.height/(float)Screen.width;​ +
- float changeAspect;​ +
-  +
- if( baseAspect > nowAspect ) +
-+
- changeAspect = nowAspect ​baseAspect;​ +
- cam.rect = new Rect( ( 1.0f - changeAspect ) * 0.5f, 0.0f, changeAspect,​ 1.0f ); +
-+
- else +
-+
- changeAspect = baseAspect ​nowAspect;​ +
- cam.rect = new Rect( 0.0f, ( 1.0f - changeAspect ) * 0.5f, 1.0f, changeAspect ); +
-+
-+
-+
-</​code>​ +
-orthographicSize とrectを調整しています。れで解像度合わせたサイズに描画されます。 +
- +
-==== 座標設定に関して ==== +
-座標設定用の関数を用意します。 +
-<code csharp>​ +
-public void SetPos ( ref GameObject _obj, float _posX, float _posY ) +
-+
- float fPixelToUnits = CameraScript.PixelToUnits;​ +
- float baseScreenWidth = CameraScript.BaseScreenWidth;​ +
- float baseScreenHeight = CameraScript.BaseScreenHeight;​ +
-  +
- Vector2 topleft = new Vector2 ( -(( baseScreenWidth * 0.5f ) / fPixelToUnits ), (( baseScreenHeight * 0.5f ) / fPixelToUnits ) ); +
-  +
- Vector2 offset = new Vector2 ( (( _posX ) / fPixelToUnits ), -(( _posY ) / fPixelToUnits ) ); +
- _obj.transform.position = new Vector3 ( topleft.x + offset.x, topleft.y + offset.y, 0.0f ); +
-+
-</​code>​ +
-直接positionを操作するのではなく、SetPos関数を実装て設定します +
-SetPos関数はSpriteの中心を(0,​ 0)と見立てて座標指定します。 +
-これを任意のGameObjectから呼び出してあげます。 +
- +
-<code csharp>​ +
-GameObject obj = gameObject;​ +
-SetPos( ref obj, 320.0f, 32.0f ); // 画像サイズが640x32なので中心に。 +
-</​code>​ +
- +
-==== 実行結果 ==== +
-{{:​wiki:​unity:​tips:​unity_aspect_adjust.png?​200|}} +
Permalink wiki/unity/tips/051.1415864811.txt.gz · 最終更新: 2015/01/06 14:15 (外部編集)

oeffentlich