Unity:How to find the value of a vector 3 allong a specific axis?

瘦欲@ 提交于 2021-01-27 19:40:30

问题


For example, you might use something like:

 public Vector3 Inertia = new Vector3();
 void Update()
 {
     Inertia += transform.TransformDirection(Vector3.forward) * Input.GetAxis("Thrust") ;
     transform.Translate(Inertia * Time.deltaTime);
 }

If you want fly a spaceship in a 3D space with all degrees of freedom. Inertia keeps track of momentum in world space while the controls add to it along the axes of the players orientation.

But, now I want to check what the players speed is along his current "forward" axes. How do you extract a value out of a vector3 along a arbitrary axes?


回答1:


If you have an arbitrary axis (call it axis), and an arbitrary vector (call it vector) and you want to find the vector component of vector in the direction of axis, you can do that with just the dot product. (see vector projection).

Scalar projection
The component of vector in the direction of axis is:

float component = Vector3.Dot(vector, axis.normalized);

Eg: If the axis was the z axis, this would be the z component of the vector.
The absolute value of component is the magnitude of the projected vector.

Vector projection
The projection of vector onto axis is:

Vector3 proj = axis.normalized * component;



回答2:


I want to check what the players speed is along his current "forward"

First of all

Inertia += transform.TransformDirection(Vector3.forward) * Input.GetAxis("Thrust") ;
transform.Translate(Inertia * Time.deltaTime);

can simply be written as

Inertia += transform.forward * Input.GetAxis("Thrust");
transform.position += Inertia * Time.deltaTime;

Then you could Project the total Inertia vector onto the transform.forward vector

Projects a vector onto another vector.

To understand vector projection, imagine that onNormal is resting on a line pointing in its direction. Somewhere along that line will be the nearest point to the tip of vector. The projection is just onNormal rescaled so that it reaches that point on the line.

and then take its magnitude

Returns the length of this vector (Read Only).

The length of the vector is square root of (x*x+y*y+z*z).

Then you can multiply it by the Dot

For normalized vectors Dot returns 1 if they point in exactly the same direction, -1 if they point in completely opposite directions and zero if the vectors are perpendicular.

var forwardSpeed = Vector3.Project(Inertia, transform.forward).magnitude * Vector3.Dot(Interia.normalized, transform.forward));


来源:https://stackoverflow.com/questions/60586769/unityhow-to-find-the-value-of-a-vector-3-allong-a-specific-axis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!