スポンサーリンク

【Unity】ワールド座標とスクリーン座標の相互変換

c#

実装

using UnityEngine;

public class WorldPointAndScreenPoint
{

    //ワールド座標をスクリーン座標に変換する
    public static Vector3 WorldPointToScreenPoint(Vector3 targetPos, Camera targetCamera)
    {
        return targetCamera.WorldToScreenPoint(targetPos);
    }

    //スクリーン座標をワールド座標に変換する
    public static Vector3 ScreenPointToWorldPoint(Vector3 targetPos, Camera targetCamera)
    {
        return targetCamera.ScreenToWorldPoint(targetPos);
    }
}

このコードでは、ワールド座標とスクリーン座標を相互変換できるよう、実装をしたものになります。

ワールド座標をスクリーン座標に変換

//ワールド座標をスクリーン座標に変換する
public static Vector3 WorldPointToScreenPoint(Vector3 targetPos, Camera targetCamera)
{
    return targetCamera.WorldToScreenPoint(targetPos);
}

Unityでは、Cameraクラスにそれぞれの座標を変換する関数が用意されています。このコードでは、ワールド座標(ゲーム中の座標)をスクリーン座標(ゲーム画面上の座標)に変換しています。

スクリーン座標をワールド座標に変換

//スクリーン座標をワールド座標に変換する
public static Vector3 ScreenPointToWorldPoint(Vector3 targetPos, Camera targetCamera)
{
    return targetCamera.ScreenToWorldPoint(targetPos);
}

こちらもCameraクラスの関数を利用して、スクリーン座標をワールド座標に変換しています。

使用例

マウスの座標からワールド座標を取得

WorldPointAndScreenPoint.ScreenPointToWorldPoint(Input.mousePosition, Camera.main);

マウスの座標を渡すことで、画面上にあるマウスカーソルの位置から、ワールド座標を取得することが出来ます。

ゲーム中にあるカメラが1つの場合は、Camera.mainでカメラを取得することが出来ます。

ゲームオブジェクトの座標からスクリーン座標を取得

 WorldPointAndScreenPoint.WorldPointToScreenPoint(target.position, Camera.main);

対象のオブジェクトの座標を渡すことで、スクリーンの座標のどの位置にオブジェクトが映っているかを、取得することが出来ます。

キャラクターの上にHPバーなどを表示する際によく使うと思います。

タイトルとURLをコピーしました