# Moving Unit Parallel to Mouse in TBS Game

I'm writing a basic Turn-Based Strategy game using Unity3D. It's not grid-based. I've come to the point where I'm coding unit movement, and I'm having trouble figuring out how far to move the units based on the mouse position. The following image is what I want:

The unit should snap forward along the red vector; it will always move in the direction it's facing. The reason I'm doing it this way is because I want the user to be able to see the result of their move, and I want to avoid some sort of GUI slider. The blue vector represents the vector from the mouse to the target point.

So, to sum it up: how do I calculate the movement (red) vector, based on the unit and mouse positions? Pseudo-code would be great!

-

## 1 Answer

It's not entirely clear, but I understand the unit will only be able to move in the direction it is facing. In that case you will need to factor that vector into the equation as well (next to the unit and mouse positions).

Have a look at the equations in Minimum Distance between a Point and a Line by Paul Bourke.

In this picture, your unit's position is `P1`, `P2` can be found by adding its facing vector to its position, and `P3` is the position of the mouse cursor. The point of intersection gives you the endpoint for the movement.

-
Do you have a link to a "codified" version of that? I tried to translate his equations into C# but my unit zoomed off into the distance... – Wackidev May 29 '12 at 22:15
I worked on it some more and now it functions as expected. Thank you! – Wackidev May 29 '12 at 23:05
@Wackidev Could you share your code? I am quite intrigued how it turned out. – Esa Jun 7 '12 at 5:14
Sure. The code snippet (it's C# using Unity3D) is here. To see it in action: here. – Wackidev Jun 7 '12 at 15:42