Legacy Documentation: Version 5.6 (Go to current version)
Computing a Normal/Perpendicular vector
Scripting Tools
Other Versions

The Amount of One Vector’s Magnitude that Lies in Another Vector’s Direction

A car’s speedometer typically works by measuring the rotational speed of the wheels. The car may not be moving directly forward (it may be skidding sideways, for example) in which case part of the motion will not be in the direction the speedometer can measure. The magnitude of an object’s rigidbody.velocity vector will give the speed in its direction of overall motion but to isolate the speed in the forward direction, you should use the dot product:-

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

Naturally, the direction can be anything you like but the direction vector must always be normalized for this calculation. Not only is the result more correct than the magnitude of the velocity, it also avoids the slow square root operation involved in finding the magnitude.

Computing a Normal/Perpendicular vector
Scripting Tools
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961