---
title: 使用矢量移动对象
product: Unity Editor
version: '6000.0'
latest_version: '7000.0'
status: This page documents version 6000.0. The latest version is 7000.0.
canonical: https://docs.unity.com/zh-cn/engine/6000.0/manual/scripting/object-oriented-development/programming-math/vectors
latest_url: https://docs.unity.com/zh-cn/engine/7000.0/manual/scripting/object-oriented-development/programming-math/vectors.md
generated_at: 2026-11-16T10:41:39.610Z
locale: zh-cn
---

# 使用矢量移动对象

> 使用 Unity 的 2D、3D 和 4D 矢量类执行矢量算术，以管理对象的位置和速度以及对象之间的距离。

矢量是一个基本的数学概念，可用于描述方向和大小。在游戏和应用程序中，矢量通常用于描述基本 Properties，例如角色的位置、移动速度或两个对象之间的距离。

矢量算术是计算机编程的许多方面（例如图形、Physics和动画）的基础，Depth了解矢量算术对于充分利用 Unity 非常有用。

矢量可以表示为多个维度，Unity 提供了二维向量、矢量 3 和矢量 4 类来处理 2D、3D 和 4D 矢量。这三种类型的矢量类All有许多相同的函数，例如大小，因此除非另有说明，否则PageON的大多数信息适用于All三种类型的矢量。

Page面Overview了 矢量 类及其在编写脚本When使用的常见用法。有关矢量类的每个成员的详尽参考，请参阅[二维向量](/engine/6000.0/script-reference/unityengine/vector2.md)、[矢量 3](/engine/6000.0/script-reference/unityengine/vector3.md) 和[矢量 4](/engine/6000.0/script-reference/unityengine/vector4.md) 的脚本参考页面。

## 了解矢量算法##understanding-vector-arithmetic

### 添加##addition

当两个向量相加时，其结果等同于将原始向量作为“步骤”，一个接一个地作为 Other。请注意，两个Parameters的Order无关紧要，因为无论哪种方式，result都是相同的。


**Vector a is a 2D vector with x component 3 and y component 5. Vector b is a 2D vector with x component 2 and y component -1. Adding a and b results in vector c, a 2D vector with x component 5 and y component 4. The relation of the three vectors to the origin point forms a scalene triangle.:**
![](/api/media?file=/engine/6000.0/media/images/VectorAdd.png)

如果第一个矢量被视为 Space 中的点，则第二个矢量可以解释为与该位置的偏移或“Jump”。例如，要查找地面ON某个位置上方 5 个单位的点，可使用以下计算：

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

如果矢量表示力，那么从它们的方向和大小来考虑它们会更直观（大小表示力的大小）。添加两个力矢量会产生一个相当于力组合的新建矢量。When同时作用多个单独组件时，此概念通常很有用（例如，正向推进的火箭也可能受到侧风的影响）。

此处的示例使用 2D 矢量，但相同的概念也适用于 3D 和 4D 矢量。

### 减法##subtraction

矢量减法最常用于获取从一个Object到另一个对象的方向和距离。请注意，两个参数的 Order 与减法**有**关系：


**2D vector a is subtracted from 2D vector b resulting in a 2D vector with x component 5 and y component 4. This is illustrated as a single line with directional arrow from point a to point b.:**
![](/api/media?file=/engine/6000.0/media/images/VectorSubtract.png)

```lang-cs
// The vector d has the same magnitude as c but points in the opposite direction.
var c = b - a;
var d = a - b;
```

与数字一样，矢量的负数的加法与正数的减法相同。

```lang-cs
// These both give the same result.
var c = a - b;
var c = a + -b;
```

矢量的负数与原始矢量具有相同的大小，并指向同一条线但方向完全相反。

## 从一个Object到另一个Object的方向和距离##direction-and-distance-from-one-object-to-another

如果从Space中的一个点减去另一个点，则result是一个从一个Object“指向”Other一个对象的矢量：

```lang-cs
// Gets a vector that points from the player's position to the target's.
var heading = target.position - player.position;
```

除了指向 Target Object 的方向之外，此矢量的大小等于两个位置之间的距离。可能需要一个“归一化”矢量提供Target的方向，但具有已修复距离（例如用于引导飞弹）。可以通过将矢量除以自身大小来对其进行归一化：

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

此方法比单独使用大小属性和归一Propertiesroperties性更可取，因为它们都十分耗费 CPU（它们都涉及计算平方根）。

如果只需要使用距离进行Comparison（例如进行接近度检查），则可以完全避免幅度计算。`sqrMagnitude` 属性给出大小值的平方，计算方式与大小相同，但没有耗时的平方根运算。您可以将平方大小与平方距离进行比较，而不是将大小与已知距离进行比较：

```lang-cs
if (heading.sqrMagnitude < maxRange * maxRange) {
	// Target is within range.
}
```

这比在 Comparison 中使用真实大小要高效得多。

有时，在 3D 模式下工作When，可能需要“俯视”Target。例如，想象一个站ON地面上的Player需要接近漂浮在空中的Target。如果从Target位置减去Player位置，则生成的矢量将向上点向Target。这不适合定向玩家的变换，因为它们也会指向上方；真正需要的是从玩家位置到 Target 正下方 ON 地面位置的矢量。您可以通过获取减法result并将 Y 坐标设置为零来获得此结果：

```lang-cs
var heading = target.position - player.position;
return 0;	// This is the overground heading.
```

## 标量乘法和除法##scalar-multiplication-and-division

When，通常将普通数量（例如浮点值）称为标量。其含义是，标量只有“缩放”或大小，而矢量同时具有大小和方向。

将矢量乘以标量会产生指向与原始方向相同的矢量。但是，新建矢量的大小等于原始大小乘以标量值。

同样，标量除法将原始矢量的大小除以标量。

When矢量表示移动偏移或作用力时，这些操作很有用。它们允许您Change矢量的大小而不影响其方向。

WhenAny矢量除以其自身的大小时，result是一个大小为 1 的矢量，称为归一归一化矢量。如果归一化矢量乘以标量，则result的大小将等于该标值。力向方向常量（强度，车轮的力终向前推动，但动力由驾驶员控制），这很有用。

## DOT 商品##dot-product

DOT 商品采用两个矢量并返回一个标量。此标量等于两个矢量全体学员的大小以及result乘以矢量之间角度的余弦。When两个矢量都归归一化时，余弦本质上表示第一个矢量在第二个矢量方向上延伸的距离（反之亦然，Parameters的Order无关紧要）。


**Two 2D vectors represented as directional lines extend from the same origin point. Vector a extends straight upward with a positive y component but no x component. Vector b extends upward by a smaller y component than vector a and to the right with a positive x component. A line describing the region of the y axis covered by both vectors is labelled as a multiplied by b.:**
![](/api/media?file=/engine/6000.0/media/images/DotProduct.png)

下面显示了与参考矢量相比角度不同的矢量如何返回 1 到 -1 之间的 DOT 商品值的 Comparison：


**A series of vectors radiate out at angles between 0 and 180 degrees from a reference vector. Between 0 and 90 degrees from the reference vector, the dot product is between 1 and 0, and decreases as the angle increases. Between 90 and 180 degrees from the reference vector, the dot product is between 0 and -1, and decreases as the angle increases.:**
![](/api/media?file=/engine/6000.0/media/images/CosineValues.png)

DOT 商品在数学上比计算余弦更简单，因此在某些情况下可以代替`Mathf.Cos`函数或矢量大小运算（其作用并不完全相同，但有时特效是等效的）。但是，计算 DOT 商品函数占用的 CPU 时间要少得多，因此它可以是一种有价值的优化。

如果要计算一个矢量的大小在另一个矢量方向上的 amount，则 DOT 商品很有用。

例如，汽车的速度计通常通过测量车轮的旋转速度来工作。汽车可能不是直接正向移动（例如，可能是侧滑），在这种情况下，部分运动不会朝向汽车的方向，因此不会由速度计测量。Object `rigidbody.velocity` 矢量的大小将给出其整体运动方向的速度，但为了隔离正向方向的速度，应使用 DOT 商品：

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

方向可以是您喜欢的任何方向，但为了进行此计算，方向矢量必须始终归一化。result不仅比速度的大小更准确，还避免了查找大小时涉及的缓慢平方根运算。

## 差乘##cross-product

差乘仅对 3D 矢量有意义。它接受两个 3D 矢量作为输入，并返回另一个 3D 矢量作为其 result。

result矢量垂直于两个输入矢量。您可以使用“右手螺丝Rule”根据输入矢量的顺序记住输出矢量的方向。如果能按输入矢量的 Order cURL，则拇指指向输出矢量的方向。如果Parameters的Order相反，则生成的矢量将点完全相反的方向，但具有相同的大小。

result的大小等于输入矢量的大小全体学员，然后值乘以它们之间角度的正弦值。正弦函数的一些有用值如下所示：


**A series of vectors radiate out at angles between 0 and 180 degrees from a reference vector. Between 0 and 90 degrees from the reference vector, the cross product is between 0 and 1, and increases as the angle increases. Between 90 and 180 degrees from the reference vector, the cross product is between 1 and 0, and decreases as the angle increases.:**
![](/api/media?file=/engine/6000.0/media/images/SineValues.png)

差乘可能看起来很复杂，因为它在其返回值中结合了几个有用的信息。但是，与 DOT 商品一样，它在数学上非常高效，可用于优化代码，否则将依赖于较慢的超越函数，例如正弦和余弦。

## 计算法线/垂直矢量##computing-a-normal/perpendicular-vector

在网格生成过程中经常需要“法线”矢量（即垂直于平面的矢量），在路径跟踪和Other情况下也很有用。给定平面中的三个点，例如网格三角形的角点，可以按如下方式查找法线：

* 从三个点中选择其中一个点
* 将其分别从Other两个点中减去（产生两个新建矢量，“Side 1”和“Side 2”）
* 计算矢量“Side 1”和“Side 2”的差乘
* 差乘的结果是垂直于三个原始点 ON 所在的平面的新建矢量 - “法线”。


**Three points; a, b, and c, in 3D coordinate space form the corner points of a triangle. Vector subtraction of b and c from a gives the long sides of the triangle, side 1 from a to b, and side 2 from a to b. The cross product of the vectors side 1 and side 2 gives a new vector perpendicular to the plane on which the three original points lie.:**
![](/api/media?file=/engine/6000.0/media/images/CalculateNormal.png)

```lang-cs
Vector3 a;
Vector3 b;
Vector3 c;

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

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


**A left hand demonstrates the left hand rule for determining the input order of vectors for calculating a cross product. The forefinger and thumb are extended at right angles to one another while the middle finger stretches out in a third plane at right angles to the forefinger. The forefinger and thumb represent the first and second input vectors to the cross product calculation respectively. The middle finger represents the resulting normal.:**
![](/api/media?file=/engine/6000.0/media/images/LeftHandRuleDiagram.png)

“Rule”可用于决定两个矢量传递给差乘函数的Order。当您在表面的顶部向下看时（法线将从该面点向外），第一个矢量应该顺时针扫向第二个矢量：

如果输入矢量的Order相反，result将点正好相反的方向。

对于网格，法线矢量也必须归一化。可以使用归一化属性性来Done此操作，但还有另一个技巧偶尔很有用。也可以通过将垂直矢量除以其大小来对其进行归一化：

```lang-cs
float perpLength = perp.magnitude;
perp /= perpLength;
```

另一个有用的注意事项是三角形的面积等于 `perpLength` / 2。如果需要查找整个网格的表面区域，或者希望根据三角形的相对区域随机选择三角形，这非常有用。

## 其他资源##additional-resources

* [二维向量 API 参考](/engine/6000.0/script-reference/unityengine/vector2.md)
* [Vector3 API 参考](/engine/6000.0/script-reference/unityengine/vector3.md)
* [Vector4 API 参考](/engine/6000.0/script-reference/unityengine/vector4.md)
