RectTransformについてのメモ

RectTransformについてのメモ

RectTransform

positionについて

RectTransfrom.position

Canvasの左下を原点とするワールド座標の位置。アンカーの場所に依存しない。Vector3を返す。

RectTransfrom.localPosition

親の中心を原点とする座標系の位置。 アンカーの場所に依存しない。 Vector3を返す。

RectTransfrom.anchoredPosition

UIのアンカーを中心とする座標系の位置。 Vector2を返す。

それぞれの関係

Cavas直下に配置されたUI要素について以下の関係が成り立ちます。

RectTransform.position == RectTransform.localPosition - new Vector2(Screen.width, Screen.height) * 0.5
offset = new Vector2(Screen.width * RectTransform.anchorMin.x, Screen.height * RectTransform.anchorMin.y);
RectTransform.position  == RectTransform.anchoredPosition + offset
offset = new Vector2(Screen.width * (0.5f - rectUI.anchorMin.x), Screen.height * (0.5f - rectUI.anchorMin.y));
RectTransform.localPosition == RectTransform.anchoredPosition - offset

Pivot

 Pivotの位置がUI要素の中心となる。Pivotを0とすると、UI要素の左下が中心となる。

アンカーについて

 アンカーの場所は親になっているUI要素に依存します。 例えば、子となっているUI要素のアンカーの数値を全て0.5とした場合は親のUI要素の中心にアンカーが配置されます。また、アンカーの数値を全て0とした場合は下図のように親要素の左下にアンカーが配置されます。

World座標をUI座標へ変換

 オブジェクトの座標をUI座標へ変換します。つまり、オブジェクトにUIが追従するようになります。

Screen Space – Overlayの場合

 CanvasのRenderModeがScreen Space – Overlayに設定してある場合は以下のScriptにより変換できます。

rectUI.position = RectTransformUtility.WorldToScreenPoint(Camera.main, trfTarget.position);

rectUIは追従させたいUI要素のRectTranformであり、trfTargetはオブジェクトのTransformです。オブジェクトのワールド座標をスクリーン座標へ変換し、そのままUI要素のpositionに渡すだけです。追従させたいUI要素に親オブジェクト等があった場合でも問題なく追従してくれます。

UI要素がCanvas直下にある場合はanchoredPosition使用した以下のScriptでも可能です。

offset = new Vector2(Screen.width * rectUI.anchorMin.x, Screen.height * rectUI.anchorMin.y);
rectUI.anchoredPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, trfTarget.position) - offset;

Screen Space – Cameraの場合

CanvasのRenderModeがScreen Space – Cameraに設定してある場合は以下のScriptにより変換できます。

Vector2 spos = RectTransformUtility.WorldToScreenPoint(Camera.main, trfTarget.position);
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(rectCanvas, spos, Camera.main, out pos);
rectUI.localPosition = pos;

オブジェクトのワールド座標をスクリーン座標へ変換し、このスクリーン座標をRectTransformUtility.ScreenPointToLocalPointInRectangleに渡すことでUI要素のローカル座標(pos)が得られます。この座標をUI要素のlocalPositionへ渡すことでオブジェクトにUIが追従するようになります。また、 追従させたいUI要素に親オブジェクト等があった場合でも問題なく追従してくれます。

UI要素がCanvas直下にある場合は、Screen Space – Overlayのときと同様のanchoredPosition使用した以下のScriptでも可能です。

offset = new Vector2(Screen.width * rectUI.anchorMin.x, Screen.height * rectUI.anchorMin.y);
rectUI.anchoredPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, trfTarget.position) - offset;