【C#】Vector3構造体をVector2構造体に変換(z成分は無視)
Vector2は2次元の情報を扱うのに適しています(x座標、y座標の情報やx軸,y軸の情報)
また、Vector3は同様に3次元の情報を扱うのに利用されます
ここでは、Vector3の情報のうち、2次元の情報のみを使いたい(z情報は不要)場合について考えてみます
目次
Vector2とVector3構造体のサンプル
次のように2つの構造体を考えてみます
public struct Vector2
{
    public float X { get; set; }
    public float Y { get; set; }
    public Vector2(float x, float y)
    {
        X = x;
        Y = y;
    }
}
public struct Vector3
{
    public float X { get; set; }
    public float Y { get; set; }
    public float Z { get; set; }
    public Vector3(float x, float y, float z)
    {
        X = x;
        Y = y;
        Z = z;
    }
}
Vector3構造体をVector2に変換する(基本サンプル)
まず、Vector3の構造体インスタンスを作成してみます
Vector3 vector3 = new Vector3(1.0f, 2.0f, 3.0f);
次にこれをVector2に変換します(z成分は無視)
Vector2 vector2 = new Vector2(vector3.X, vector3.Y);
Console.WriteLine($"Vector2: X = {vector2.X}, Y = {vector2.Y}");
実行結果
Vector2: X = 1, Y = 2
Vector3構造体をVector2に変換する(明示的なキャスト)
明示的にキャスト(変換)できるように変更したVector2構造体
public struct Vector2
{
    public float X { get; set; }
    public float Y { get; set; }
    public Vector2(float x, float y)
    {
        X = x;
        Y = y;
    }
    // Vector3からVector2への変換演算子をオーバーロード
    // explicitは明示的なキャスト
   public static explicit operator Vector2(Vector3 vector3)
    {
        return new Vector2(vector3.X, vector3.Y);
    }
}
これを使うと、Vector2への変換は次のようにできます(z成分は無視)
Vector2 vector2 = (Vector2)vector3;
Vector3構造体をVector2に変換する(暗黙的なキャスト)
暗黙的にキャスト(変換)できるように変更したVector2構造体
public struct Vector2
{
    public float X { get; set; }
    public float Y { get; set; }
    public Vector2(float x, float y)
    {
        X = x;
        Y = y;
    }
    // Vector3からVector2への変換演算子をオーバーロード
    // implicitは暗黙的なキャスト
   public static implicit operator Vector2(Vector3 vector3)
    {
        return new Vector2(vector3.X, vector3.Y);
    }
}
これを使うと、Vector2への変換は次のようにできます(z成分は無視)
Vector2 vector2 = vector3;
訪問数 79 回, 今日の訪問数 1回






ディスカッション
コメント一覧
まだ、コメントがありません