LoginSignup
1
0

More than 3 years have passed since last update.

C#の拡張メソッドでVector3 にオレオレメソッドを追加する

Last updated at Posted at 2018-12-05

たとえば三次元空間上のオブジェクトの位置情報を地図などのUIに表示したい時など、オブジェクトのx,zを地図のx,y上に変換するために

Vector2 mapPos = new Vector2(playerPos.x,playerPos.z);

のようにすることがあるかと思いますが、
Vector3(x,y,z)->Vector2(x,z)
Vector2(x,y)->Vector3(x,0,z)
を頻繁に行う必要がある場合、毎回 new Vector2(v.x,v.z) のようにするのは面倒です。
そんな時はVector3にC#の拡張メソッドを追加すると便利です。

[OreOreExtensionMethods.cs]
public static class OreOreExtensionMethods
{
    /// <summary>
    /// To Vector2(x,z) from Vector3(x,y,z) 
    /// </summary>
    public static UnityEngine.Vector2 ToVec2XZ(this UnityEngine.Vector3 v)
    {
        return new UnityEngine.Vector2(v.x, v.y);
    }

    /// <summary>
    /// To Vector3(x,0,y) from Vector2(x,y) 
    /// </summary>
    public static UnityEngine.Vector3 ToVec3X0Y(this UnityEngine.Vector2 v)
    {
        return new UnityEngine.Vector3(v.x, 0f, v.y);
    }
}

こんなファイルをプロジェクトに入れておくと、
2018-12-06_040201.png

こんな感じでオレオレメソッドが使えるようになります。

1
0
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
1
0