Version: 2021.3

# 重要的类 - 矢量

Vectors are a fundamental mathematical concept which allow you to describe a direction and magnitude. In games and apps, vectors are often used to describe some of the fundamental properties such as the position of a character, the speed something is moving, or the distance between two objects.

## 了解矢量算术

### 加法

`````` var pointInAir = pointOnGround + new Vector2(0, 5);
``````

### 减法

``````// 矢量 d 的大小与 c 相同，但指向相反的方向。
var c = b - a;
var d = a - b;

``````

``````// 这两者得出相同的结果。
var c = a - b;
var c = a + -b;

``````

## 从一个对象到另一个对象的方向和距离

``````// 获取从玩家位置指向目标位置的矢量。
var heading = target.position - player.position;

``````

``````var distance = heading.magnitude;
var direction = heading / distance; // This is now the normalized direction.
``````

``````if (heading.sqrMagnitude < maxRange * maxRange) {
// 目标在范围内。
}
``````

``````var heading = target.position - player.position;
``````

## 点积

``````var fwdSpeed = Vector3.Dot(rigidbody.velocity, transform.forward);
``````

## 叉积

The result vector is perpendicular to the two input vectors. You can use the “right hand screw rule” to remember the direction of the output vector from the ordering of the input vectors. If you can curl your fingers in the order of the input vectors, your thumb points in the direction of the output vector. If the order of the parameters is reversed then the resulting vector will point in the exact opposite direction but will have the same magnitude.

## 计算法向/垂直矢量

``````Vector3 a;
Vector3 b;
Vector3 c;

Vector3 side1 = b - a;
Vector3 side2 = c - a;

Vector3 normal = Vector3.Cross(side1, side2);
``````

``````float perpLength = perp.magnitude;
perp /= perpLength;
``````