Unityでワールド座標からCanvas上の座標に変換

2015-07-15

ワールドの座標位置に合わせてUIなどを表示したい場合の計算方法:

  1. 使ってるカメラの WorldToViewportPoint で、ワールド座標系からビューポート座標系に変換
  2. CanvasRectTransform のサイズの1/2を引く(ビューポートは左下が原点なのに対して、 Canvas は中央が原点のため)

Unity 4.6 Beta 19: How to convert from world space to canvas space - Unity Answers

//this is your object that you want to have the UI element hovering over
GameObject WorldObject;

//this is the ui element
RectTransform UI_Element;

//first you need the RectTransform component of your canvas
RectTransform CanvasRect = Canvas.GetComponent<RectTransform>();

//then you calculate the position of the UI element
//0,0 for the canvas is at the center of the screen, whereas WorldToViewPortPoint treats the lower left corner as 0,0. Because of this, you need to subtract the height / width of the canvas * 0.5 to get the correct position.

Vector2 ViewportPosition = Cam.WorldToViewportPoint(WorldObject.transform.position);
Vector2 WorldObject_ScreenPosition = new Vector2(
((ViewportPosition.x * CanvasRect.sizeDelta.x) - (CanvasRect.sizeDelta.x * 0.5f)),
((ViewportPosition.y * CanvasRect.sizeDelta.y) - (CanvasRect.sizeDelta.y * 0.5f)));

//now you can set the position of the ui element
UI_Element.anchoredPosition = WorldObject_ScreenPosition;