LoginSignup
13
13

More than 5 years have passed since last update.

3Dのオブジェクトの表示位置に2DのUIオブジェクト追随させる

Last updated at Posted at 2014-10-17

3Dのオブジェクトは Perspective なカメラ、2Dのオブジェクトは Orthographic なカメラにそれぞれ投影されている前提。

以下の手順で 3D オブジェクトの座標を 2D オブジェクトの座標に反映させる。

  • 3Dオブジェクトのワールド座標から、Perspective カメラのビューポート座標を求める
  • 上記ビューポート座標を Orthographic カメラのワールド座標に逆変換する
  • 求めたワールド座標を 2Dオブジェクトの transform.position に設定する

コード例

sample.cs

GameObject obj3d;       // 3Dオブジェクト
GameObject obj2d;       // 2Dオブジェクト

Camera perspCamera;  // 3Dオブジェクトを写すカメラ
Camera orthoCamera;  // 2Dオブジェクトを写すカメラ

// 3Dオブジェクトのワールド座標から、Perspective カメラのビューポート座標を求める 
var viewPortPos = perspCamera.WorldToViewPortPoint(obj3d.transform.position);
// 上記ビューポート座標を Orthographic カメラのワールド座標に逆変換する
var worldPos2d = orthoCamera.ViewportToWorldPoint(viewPortPos);
// 2Dオブジェクトの座標を移動
obj2d.transform.position = worldPos2d;

参考: UnityのCameraが使う3つの座標系 - テラシュールブログ

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13