# More simple vector math...

I want to determine a particular object's velocity along a given vector. Let's say I have a cube on its side, and the cube's "Up" is pointing to the left.

I want to find how fast an object is traveling along the cube's up, then stop all movement along that cube's "up" axis.

IE: (velocity along cube's up).y = 0;

How might I do this?

EDIT: I'm working only with Vector3. I have Vector3 cubeUp, and Vector3 objectVelocity, trying to figure out objectVelocity relative to cubeUp. Vector3.Dot doesn't seem to be what I need. Maybe Vector3.Slerp?

Dot is in fact what you want. You take the dot product of the Up vector and the velocity's direction - this gives you a number which is the amount of the velocity vector that was going Up. (It will be 1 if they are going the same direction, 0 if right angles to each other.)

For Dot to work you need normalized vectors (i.e. of length 1). Up is already normalized, you just need to use velocity.normalized.

Once you have Dot, you will want to multiply it by the magnitude of the original velocity vector. This gives you a vector pointing Up which is the component of the original velocity that was moving Up.

By subtracting that vector from the original velocity vector, you will end up with a new vector with the Up component cancelled out.

Here is another Answer that is using Dot. (It's only checking whether something is moving towards an object or away from it, so it doesn't do the multiple or subtract steps.) http://answers.unity3d.com/questions/12595/help-with-vector3-dot-please

Yours will look something like this (note: not debugged code.)

``````Vector3 upComponent = velocity.magnitude * Vector3.Dot(upVector, velocity.normalized);
Vector3 newVelocity = velocity - upComponent;

``````

You need to use the InverseTransformDirection function here. Let's say "Sphere" is the moving object to test, and you want to find out how fast it's moving along the cube's local "up" axis:

``````var v = sphere.rigidbody.velocity;
var relativeVelocity = cube.transform.InverseTransformDirection( v );

``````

You can then test "relativeVelocity.y" to find out the sphere's speed along the cube's up axis. If you want to set that to zero, and assign it back to the sphere, you can do this:

``````relativeVelocity.y = 0;
var newVelocity = cube.transform.TransformDirection( relativeVelocity );
sphere.rigidbody.velocity = newVelocity;

``````

It's worth noting however, that it's generally advised against setting object's velocities directly as it can result in unpredictable and erratic results from the physics engines - so use with caution!

In my experience it seems to be okay if the velocity changes don't interfere with other objects (eg, causing an collision that was not expected by the physics engine).