Vector3向量相关

Unity 向量(Vector3)核心知识总结

一、常用属性与基本操作

1. 向量基本属性

用法 含义
v.magnitude 向量长度(模)
v.normalized 单位向量(方向不变、长度=1)
Vector3.Distance(A,B) 两点间距离

2. 向量常见用途

  • 求方向:(B - A).normalized
  • 求速度方向:velocity.normalized
  • 求移动:transform.position += dir * speed * Time.deltaTime

二、向量运算(Dot 点乘|Cross 叉乘)

1. Dot(点乘)——判断角度、判断前后

公式:

A·B = Ax*Bx + Ay*By + Az*Bz
A·B = |A||B|cosθ

判断夹角特性:

  • A·B > 0 → 锐角
  • A·B = 0 → 直角
  • A·B < 0 → 钝角

求两向量夹角:

float angle = Vector3.Angle(A, B); // 内部用的是 acos(dot)

判断对象在自身前后:

float frontBack = Vector3.Dot(transform.forward, target.position - transform.position);
// >0 前方   <0 后方

2. Cross(叉乘)——判断左右、求垂直方向

公式:

A×B = (AyBz - AzBy, AzBx - AxBz, AxBy - AyBx)

特点:

  • 返回一个 垂直于 A 和 B 的向量
  • A×B = −(B×A)
  • 根据方向可判断 左右关系

判断左右:

float leftRight = Vector3.Cross(transform.forward, target.position - transform.position).y;
// >0 在右侧   <0 在左侧

三、判断与功能实现(前后|左右|上下)

1. 仅用点乘判断方位

Vector3 toTarget = target.position - transform.position;

float frontBack = Vector3.Dot(transform.forward, toTarget);  // 前后
float leftRight = Vector3.Dot(transform.right,   toTarget);  // 左右
float upDown    = Vector3.Dot(transform.up,      toTarget);  // 上下

推荐:判断前后/上下用点乘,左右用叉乘更直观


2. 点乘 + 叉乘组合判断左右

Vector3 toTarget = target.position - transform.position;

float frontBack = Vector3.Dot(transform.forward, toTarget);  
float leftRight = Vector3.Cross(transform.forward, toTarget).y;

四、常用功能示例

1. 判断敌人是否在视野前方

if (Vector3.Dot(transform.forward, toTarget) > 0)
{
    // 在前方
}

2. 计算视角内夹角

float angle = Vector3.Angle(transform.forward, toTarget);
if (angle < viewAngle * 0.5f)
{
    // 在视野范围内
}

3. 判断敌人在左还是右

float side = Vector3.Cross(transform.forward, toTarget).y;

4. 求垂直方向(如向上力、法线方向)

Vector3 normal = Vector3.Cross(A, B).normalized;

posted @ 2025-11-30 19:01  高山仰止666  阅读(1)  评论(0)    收藏  举报