Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

Ideal Behavior

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!

share|improve this question
up vote 3 down vote accepted

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.

Picture from Paul Bourke's Minimum Distance between a Point and a Line

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.

share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.