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.
Answer
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;
No comments:
Post a Comment