screen距離をworld距離に変換する
2020/09/07
Unity
2D
screen
Unityの2D環境でscreen座標上の距離をworld座標上の距離に変換する
環境
- Unity 2020.1.3f1
実装
/// <summary>
/// スクリーン距離をワールド距離に変換する
/// </summary>
/// <param name="camera">対象のカメラ</param>
/// <param name="screenDelta">スクリーン上の距離</param>
/// <returns></returns>
public static Vector2 ConvertScreenDeltaToWorldDelta(this Camera camera, Vector2 screenDelta)
{
Vector3 p1 = camera.ScreenToWorldPoint(Vector3.zero);
Vector3 p2 = camera.ScreenToWorldPoint(Vector3.right);
float unit = p2.x - p1.x;
return screenDelta * unit;
}
screen上の点をworld座標に変換するのはCamera.ScreenToWorldPointメソッド[1]が利用できる。
(1, 0, 0)と(0, 0, 0)の距離の差分が1pxあたりのworld距離(unit
)になるので、screen距離にこれを掛ければworld距離になる。