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!


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.

  • \$\begingroup\$ 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... \$\endgroup\$
    – Wackidev
    May 29 '12 at 22:15
  • 1
    \$\begingroup\$ I worked on it some more and now it functions as expected. Thank you! \$\endgroup\$
    – Wackidev
    May 29 '12 at 23:05
  • \$\begingroup\$ @Wackidev Could you share your code? I am quite intrigued how it turned out. \$\endgroup\$
    – Esa
    Jun 7 '12 at 5:14
  • 1
    \$\begingroup\$ Sure. The code snippet (it's C# using Unity3D) is here. To see it in action: here. \$\endgroup\$
    – Wackidev
    Jun 7 '12 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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