# Calculate speed an object is moving towards another direction

The title probably sucks because this is a really hard question to word properly, so I apologize for that.

Basically I have these two variables: moveSpeed and moveDirection. I'm using these to move an object at that speed in that direction. However, I want to find out how much of that speed is going in another direction.

So, for example

moveSpeed=10
moveDirection=80
otherSpeed=x
otherDirection=70


We have an object moving 80 degrees at 10 pixels per frame. How much of that speed is it moving 70 degrees? Also I realize (and expect) that this number will be negative when the direction is on the opposite side of the circle.

Also, here's a picture to make a little more sense.

Common sense tells us the speed is ~9 since the other direction is very close to the initial direction.

And if I still did too terrible of a job explaining, some static examples:

With 10 moveSpeed in 0 moveDirection, I'd get -10 otherSpeed at 180 otherDirection

With 10 moveSpeed in 0 moveDirection, I'd get 0 otherSpeed at 90 otherDirection

With 10 moveSpeed in 0 moveDirection, I'd get 5 otherSpeed at 45 otherDirection

So, what formula would I plug moveSpeed, moveDirection, and otherDirection into to get otherSpeed?

-
Your intuition is pretty good, except that you would get otherSpeed of $10\cos45^\circ\approx7.071$ at otherDirection = 45. Imagine walking $10$ units along the diagonal of a $10$ unit square; you get farther than halfway. – Rahul Jan 9 '13 at 19:21

What you are looking for is called the projection formula. If you have a vector A and you want to find its projection vector on vector B then you use $S= {{A\cdot B}\over {B\cdot B}} B$. Here $A$ is your original velocity vector $A=10(\cos80, \sin80)$. And $B$ is your new direction $B=(\cos70,\sin70)$. And the dot product is defined by $A\cdot B=a_1b_1+a_2b_2=10(\cos80\cos70+\sin80\sin70)$, which using a formula from trig is $10\cos(80-70)=10\cos10$. Your $B \cdot B$ is just $1$, as $B$ is a unit vector. So your velocity in the new direction is $10\cos10(\cos70,\sin70)$. Your speed in that direction is $10\cos10$.