うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】2つの単位ベクトル間の角度を取得する

単位ベクトルから、角度を取得するメソッドが欲しくて作成すると以下になる

using UnityEngine;
 
public class Utility
{
    /// <summary>
    /// 2つの単位ベクトル間の角度を取得
    /// </summary>
    public static float SignedAngle(Vector2 a, Vector2 b)
    {
        // dot(a, b) = cos(b - a)
        var dot = Vector2.Dot(a, b);
        // 行列式を利用して外積 (sin(b - a)を取得)
        var sin = a.x * b.y - a.y * b.x;
        // Atan2 で sin, con を利用して角度を取得 
        return Mathf.Atan2(sin, dot) * Mathf.Rad2Deg;
    }
}

しかし、Vector2 にすでに関数が存在していたため、こちらを利用したほうが早い

    /// <summary>
    ///   <para>Returns the signed angle in degrees between from and to.</para>
    /// </summary>
    /// <param name="from">The vector from which the angular difference is measured.</param>
    /// <param name="to">The vector to which the angular difference is measured.</param>
    public static float SignedAngle(Vector2 from, Vector2 to) => Vector2.Angle(from, to) * Mathf.Sign((float) ((double) from.x * (double) to.y - (double) from.y * (double) to.x));