「Unity/3d/3dから2dの座標変換」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→CanvasのRenderModeによってやり方が違う) |
|||
| (同じ利用者による、間の6版が非表示) | |||
| 行51: | 行51: | ||
==CanvasのRenderModeによってやり方が違う== | ==CanvasのRenderModeによってやり方が違う== | ||
| − | 上記は"World Space- Camera" | + | 上記は"World Space- Camera"でのやり方であって、ScreenPointToLocalPointInRectangle(canvasRect, screenPos, uiCamera, out pos);の部分を以下のように変更する。 |
| − | * | + | *Overlayの場合は、 |
| − | * | + | <pre> |
| + | var screenPos = RectTransformUtility.WorldToScreenPoint(worldCamera, position); | ||
| + | pos = canvas.transform.InverseTransformPoint(screenPos); | ||
| + | GetComponent<RectTransform>().localPosition = pos; | ||
| + | </pre> | ||
| + | *WorldSpaceの場合は、 | ||
| + | <pre> | ||
| + | RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, screenPosition, Camera.main, out result); | ||
| + | </pre> | ||
参考:https://appleorbit.hatenablog.com/entry/2015/10/23/000403 | 参考:https://appleorbit.hatenablog.com/entry/2015/10/23/000403 | ||
2022年8月28日 (日) 04:10時点における最新版
3dから2dの座標変換のサンプル
LabelTextのGameObjectに以下csをAddComponentsする。
LabelPosition.cs
using UnityEngine;
public class LabelPosition : MonoBehaviour
{
[SerializeField]
public Camera mainCamera, uiCamera;
[SerializeField]
public GameObject cube;
[SerializeField]
public Canvas canvas;
void Update()
{
var pos = Vector2.zero;
var worldCamera = mainCamera;
var canvasRect = canvas.GetComponent<RectTransform>();
Vector3 position =
new Vector3(
cube.transform.position.x,
cube.transform.position.y + 1f,
cube.transform.position.z
);
var screenPos = RectTransformUtility.WorldToScreenPoint(worldCamera, position);
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPos, uiCamera, out pos);
this.GetComponent<RectTransform>().localPosition = pos;
}
}
呼び出し方サンプル
Example.cs
void LabelCall() {
Camera camera = GameObject.Find("FPS Camera").GetComponent<Camera>();
GameObject enemy = GameObject.Find("EnemyObject");
GameObject obj = GameObject.Find("LabelText");
LabelPosition labelPosition = obj.GetComponent<LabelPosition>();
labelPosition.mainCamera = camera;
labelPosition.uiCamera = camera;
labelPosition.cube = enemy;
labelPosition.canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
}
参考:http://tsubakit1.hateblo.jp/entry/2016/03/01/020510
CanvasのRenderModeによってやり方が違う
上記は"World Space- Camera"でのやり方であって、ScreenPointToLocalPointInRectangle(canvasRect, screenPos, uiCamera, out pos);の部分を以下のように変更する。
- Overlayの場合は、
var screenPos = RectTransformUtility.WorldToScreenPoint(worldCamera, position); pos = canvas.transform.InverseTransformPoint(screenPos); GetComponent<RectTransform>().localPosition = pos;
- WorldSpaceの場合は、
RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, screenPosition, Camera.main, out result);
参考:https://appleorbit.hatenablog.com/entry/2015/10/23/000403
