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

Viewed 1113

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?

2 Answers

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;

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.

enter image description here

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));
Related