b

vec{b}

b

a

vec{a}

a

b

vec{b}

b

# 4 应用案例

## 4.1 求两向量的夹角

    /// <summary>
///   <para>Returns the 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>
/// <returns>
///   <para>The angle in degrees between the two vectors.</para>
/// </returns>
public static float Angle(Vector3 from, Vector3 to)
{
float num = (float) Math.Sqrt((double) from.sqrMagnitude * (double) to.sqrMagnitude);
if ((double) num < 1.00000000362749E-15)
return 0.0f;
return (float) Math.Acos((double) Mathf.Clamp(Vector3.Dot(from, to) / num, -1f, 1f)) * 57.29578f;
}


a

vec{a}

a

·

b

vec{b}

b

=0。

a

vec{a}

a

b

vec{b}

b

a

vec{a}

a

·

b

vec{b}

b

=0，就说明两向量垂直。

## 4.3 判断NPC是否在攻击范围内

A

B

vec{AB}

AB

A

B

vec{AB}

AB

// 判断targetPos是否在视线范围内
public bool IsInView(Vector3 targetPos)
{
// 玩家位置
Vector3 selfPos = m_GameObject.transform.position;

if (Vector3.Distance(selfPos, targetPos) > 10f)
return false;

Vector3 loorDir = targetPos - selfPos;
if (Vector3.Angle(loorDir, m_GameObject.transform.forward) < 30f)
return true;

return false;
}


## 4.4 已知入射光线和表面法线求反射光线

A

O

vec{AO}

AO

n

vec{n}

n

（假定为单位向量），求反射光线

O

B

vec{OB}

OB

b

vec{b}

b

a

vec{a}

a

b

vec{b}

b

O

P

vec{OP}

OP

O

A

vec{OA}

OA

n

vec{n}

n

O

P

vec{OP}

OP

n

vec{n}

n

，咱们就求到

O

P

vec{OP}

OP

/// <summary>
/// 计算反射光线
/// </summary>
/// <param name="lightDir">入射光线</param>
/// <param name="normalDir">表面法线(单位向量)</param>
/// <returns>反射光线</returns>
private Vector3 CalcReflectDir(Vector3 lightDir, Vector3 normalDir)
{
return lightDir - 2 * Vector3.Dot(lightDir, normalDir) * normalDir;
}


THE END