# Detecting Vector3 Movement speed.

Hello, I’m currently making a space type movement system.

My current movement script so far is stated below.

``````        if (Input.GetKey(KeyCode.W))

if (Input.GetKey(KeyCode.S))

if (Input.GetKey(KeyCode.D))

if (Input.GetKey(KeyCode.A))

if (Input.GetKey(KeyCode.Space))

if (Input.GetKey(KeyCode.LeftControl))

``````

So far this works perfectly for what I want it for. Now i’m also trying to make it so when a player lets go of the movement the ship auto stops.

For example.

If the ship is moving foward, engage front thrusters to push it back.

I have looked all over and can not find a way to detect if Vector3.foward speed is bigger than 0.

Can anybody help me with this?

Thanks.

Dot products (http://en.wikipedia.org/wiki/Dot_product) are useful for this! A useful property of dot products is:

A · B = ||A|| ||B|| cosθ

Where θ is the angle in between A and B.

So, if we take the ship’s velocity vector and take the dot product with the forward vector, we very conveniently get a scalar value that represents how fast the ship is moving in the forward direction (note: this works out because Vector3.forward is normalized, so ||B|| in the equation above is 1, and nicely drops out of the equation).

``````float forwardSpeed = Vector3.Dot(rigidbody.velocity, Vector3.forward);
if (forwardSpeed > 0)
{
// going in the forward direction forwardSpeed units / second!
// better slow down!
}
else if (forwardSpeed < 0)
{
// we're going backward at ||forewardSpeed|| units / second!
}
``````

function Start(){
rigidbody.drag = 1;
rigidbody.angularDrag = 1;
}

Drag is used to stop a rigidbody when no force is being applied to it.