【Unity】2点間の距離を計算したい

Vector3構造体に距離計算のメソッドが用意されていますので活用することで算出が可能です

テストコード

Vector3 positon1 = new Vector3(3, 4, 5);
Vector3 positon2 = new Vector3(1, 2, 3);

Debug.Log((positon1 - positon2).magnitude);
Debug.Log(Vector3.Distance(positon1, positon2));

結果

UnityエンジンのVector3構造体内のコード

public float magnitude
{
    get
    {
        return (float)Math.Sqrt(x * x + y * y + z * z);
    }
}
public static float Distance(Vector3 a, Vector3 b)
{
    float num = a.x - b.x;
    float num2 = a.y - b.y;
    float num3 = a.z - b.z;
    return (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3);
}

オペレータ演算子のオーバーロード

public static Vector3 operator -(Vector3 a, Vector3 b)
{
    return new Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
}

C#,Unity

Posted by hidepon