n-yoda's blog

主にUnity3Dに関するあんまり技術的じゃないメモ的な何かを書いています。

UnityでGUIの回転・変形などなど(GUI.matrix)

OnGUIで描画するGUIの回転・変形の仕方まとめ。

行列がわかる人はGUI.matrixに、自分で定義したMatrix4x4を代入してあれこれ出来ると思いますが、

普段主に使うのは↓です。
・指定座標を中心に回転 GUIUtility.RotateAroundPivot
・指定座標を中心に拡大 GUIUtility.ScaleAroundPivot

サンプルコードです。

public Texture box;
public Texture triangle;

void OnGUI ()
{
	// 中心を軸にに回転
	Rect rect0 = new Rect (20, 20, 100, 100);
	GUIUtility.RotateAroundPivot (30f, rect0.center);
	GUI.DrawTexture (rect0, box);
	
	// RotateAroundPivot等は行列の掛け算なので、一旦初期値に戻す
	GUI.matrix = Matrix4x4.identity;
			
	// iPhone(縦)座標
	GUIUtility.ScaleAroundPivot (new Vector2 (Screen.width / 640f, Screen.height / 960f), Vector2.zero);
	Rect iRect = new Rect (560, 880, 80, 80);
	GUI.DrawTexture (iRect, box);
		
	// Event.current.mousePositionの座標も勝手に変換されるので当たり判定も楽
	if (iRect.Contains (Event.current.mousePosition)) {
		print ("Mouse Over");
	}
}

注意など

GUI.matrix = Matrix4x4.identity;

GUI.matrixは一度設定するとそれ以降全部に適応されるので、元に戻すこと。


if (iRect.Contains (Event.current.mousePosition))
	print ("Mouse Over");

Event.current.mousePositionはGUI.matrixの逆変換を受けるので、クリック判定部分を書き換える必要はありません。
(つまり逆行列を持たないMatrixを指定するとエラー)


GUIElementみたいに、0〜1の相対座標にしたいな〜と思って

GUIUtility.ScaleAroundPivot (new Vector2 (Screen.width, Screen.height), Vector2.zero);
GUI.Button (new Rect (0, 0, 0.3f, 0.3f), texture);

としてみたところ、上手く動きませんでした(;;) (ver 3.5.2)
GUIにRectを渡すタイミングで小数点が丸められているかも?