Vector2.Angle
/ Vector3.Angle
)Unityでは、Vector2
やVector3
クラスに、2つのベクトル間の角度を直接計算する便利な関数があります。
float angle = Vector2.Angle(Vector2 from, Vector2 to);
from
ベクトルとto
ベクトルの間の角度を計算します。float angle = Vector3.Angle(Vector3 from, Vector3 to);
from
ベクトルとto
ベクトルの間の角度を計算します。例:
Vector3 from = new Vector3(1, 0, 0); // X軸方向のベクトル
Vector3 to = new Vector3(0, 1, 0); // Y軸方向のベクトル
float angle = Vector3.Angle(from, to); // 結果は90度
Vector3.Angle
やVector2.Angle
は内積を使って角度を計算しており、コードがシンプルで、計算精度も高いです。
ベクトルの内積を使って、2つのベクトル間の角度を求めることもできます。内積を使った計算は、次の式を使用します:
\[cos(\theta) = \frac{A \cdot B}{|A| |B|} \\]ここで、A
とB
は2つのベクトル、A·B
は内積、|A|
と|B|
はそれぞれベクトルの長さ(ノルム)です。
この式を使って、角度をラジアンで求め、Mathf.Rad2Deg
で度数法に変換できます。
float angleInRadians = Mathf.Acos(Vector3.Dot(from.normalized, to.normalized));
float angleInDegrees = angleInRadians * Mathf.Rad2Deg;
例:
Vector3 from = new Vector3(1, 0, 0); // X軸方向のベクトル
Vector3 to = new Vector3(0, 1, 0); // Y軸方向のベクトル
float angleInRadians = Mathf.Acos(Vector3.Dot(from.normalized, to.normalized));
float angleInDegrees = angleInRadians * Mathf.Rad2Deg; // 結果は90度
回転行列を使って角度を求める方法もあります。特に3D空間で、オブジェクトがどれくらい回転したかを求める際に有効です。Unityでは、Quaternion
を使って回転を表現できます。
例えば、オブジェクトの回転を角度に変換する場合:
Quaternion rotation = transform.rotation;
float angle = rotation.eulerAngles.y; // Y軸の回転角度(度数法)
Mathf.Atan
)Mathf.Atan
は、与えられたy
とx
の比(すなわち、傾き)から角度を求める関数です。
Mathf.Atan(y / x)
: 与えられたx軸、y軸の比を使って、角度をラジアンで返します。これは、Mathf.Atan2
と似ていますが、Mathf.Atan2
は座標の正負を考慮するため、より広い範囲(-180度から180度)を返します。一方、Mathf.Atan
は-π/2からπ/2の範囲に限定されます。
float angleInRadians = Mathf.Atan(y / x);
float angleInDegrees = angleInRadians * Mathf.Rad2Deg;
例:
float x = 1.0f;
float y = 1.0f;
float angleInRadians = Mathf.Atan(y / x);
float angleInDegrees = angleInRadians * Mathf.Rad2Deg; // 結果は45度
Vector3.SignedAngle
(3D空間での角度)Vector3.SignedAngle
は、2つの3Dベクトル間の角度を求める際に、回転方向(符号付き)も考慮して計算する関数です。
float angle = Vector3.SignedAngle(from, to, axis);
from
: 最初のベクトルto
: 目標のベクトルaxis
: 角度の回転軸(例えばVector3.up
でY軸回転)Vector3.SignedAngle
は、回転方向も含めた角度を計算するため、-180度から180度の範囲で角度を返します。
例:
Vector3 from = new Vector3(1, 0, 0);
Vector3 to = new Vector3(0, 1, 0);
Vector3 axis = Vector3.up;
float angle = Vector3.SignedAngle(from, to, axis); // 結果は90度
角度を求める方法は用途に応じてさまざまです。代表的なものは次の通りです:
Mathf.Atan2
: 座標から角度を計算する標準的な方法。Vector2.Angle
/ Vector3.Angle
: 2つのベクトル間の角度を直接計算。Vector3.SignedAngle
: 3D空間で、符号付きで角度を求める方法。目的に応じて適切な方法を選んで使うことができます。例えば、オブジェクト間の回転を計算したいときはVector3.Angle
やVector3.SignedAngle
が便利で、ターゲット方向を求める場合はMathf.Atan2
がよく使われます。