# Making a player move to my mouse when clicked?

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.

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.

Example:

previousMouseX;
previousMouseY;

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;

• Good point. Let me edit. Commented Feb 2, 2013 at 0:23
• That should do it! Commented Feb 2, 2013 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 : gamedev.stackexchange.com/questions/48119/… Commented Feb 2, 2013 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.