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

How can I get my player to move to the mouse when it is clicked (like in Warcraft)?

So far I have tried:

if (Mouse.isButtonDown(0)) {

    if (X < Mouse.getX()) {
        X += Speed;
    if (X > Mouse.getX()) {
        X -= Speed;
    if (Y < Mouse.getY()) { 
        Y += Speed;
    if (Y > Mouse.getY()) {
        Y -= Speed;

But that only does what I want if I hold the mouse down.

share|improve this question
up vote 4 down vote accepted

What I'd do is create 2 new variables that will hold the Mouse.Y() and Mouse.X() and set them when you click. Say we call them previousMouseX and previousMouseY.

Now, in your update method, we need to get the distance between your coördinates. That'll be Mouse.Y() - Y, same thing for the X distance.

After this we will get the angle of the movement so it moves in a straight line to the previousMouse X and Y. We will use sinus and cosinus for this. Then we multiply this by the speed so the object moves at the speed you want.



differenceX = previousMouseX - X;
differenceY = previousMouseY - Y;

angle = (float)Math.Atan2(differenceY, differenceX) * 180 / Math.PI;

X += Math.cos(angle * Math.PI/180) * Speed;
Y += Math.sin(angle * Math.PI/180) * Speed;
share|improve this answer
Good point. Let me edit. – Randy Schouten Feb 2 '13 at 0:23
That should do it! – Randy Schouten Feb 2 '13 at 0:42
You can omit the whole cos and sin call if you divide differenceX/Y with it's length and multiply that with your speed. See my answer to a different post :… – Sidar Feb 2 '13 at 0:55

Right, so you can't move at a set speed on both the X and Y axis. What you're doing now will mean that objects move faster moving diagonally then in the X or Y direction.

What you're better off doing is finding the angle between your player location and mouse location and then moving the player with a certain speed in that direction.

share|improve this answer

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.