1

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.

Lucius
  • 3,705
  • 2
  • 22
  • 41
  • For information only, you might want to google "game engine". Nobody writes a game from scratch these days. – gerrytan Feb 01 '13 at 23:11
  • You might also want to move this into the gamedev stackexchange. – Daniel Kaplan Feb 01 '13 at 23:14
  • @gerrytan If that is true, how can you explain *over 4000 XNA questions* here on SO? There is nothing to say against building a small game from scratch. A game engine is often complete overkill for smaller projects. – Lucius Feb 01 '13 at 23:20

1 Answers1

3

Simply store the position of the last click and let the player move in that direction.

Add these fields to your player class:

int targetX;
int targetY;

In your update method store the new target and apply the movement:

// A new target is selected
if (Mouse.isButtonDown(0)) {

    targetX = Mouse.getX();
    targetY = Mouse.getY();
}

// Player is not standing on the target
if (targetX != X || targetY != Y) {

    // Get the vector between the player and the target
    int pathX = targetX - X;
    int pathY = targetY - Y;

    // Calculate the unit vector of the path
    double distance = Math.sqrt(pathX * pathX + pathY * pathY);
    double directionX = pathX / distance;
    double directionY = pathY / distance;

    // Calculate the actual walk amount
    double movementX = directionX * speed;
    double movementY = directionY * speed;

    // Move the player
    X = (int)movementX;
    Y = (int)movementY;
}
Lucius
  • 3,705
  • 2
  • 22
  • 41
  • I replaced the code in the update method and with yours and added the 2 variables at the top but it didn't work –  Feb 01 '13 at 23:45
  • 1
    @griffy100 I won't write your game for you, pal. – Lucius Feb 01 '13 at 23:54
  • I modified your code and made it a lot simpler AND IT WORKED: `if(Mouse.isButtonDown(0)){ TargetX=Mouse.getX(); TargetY=Mouse.getY(); } if(XTargetX){X-=Speed;} if(YTargetY){Y-=Speed;}` –  Feb 02 '13 at 00:08
  • 1
    Yes, that works as well. There are two differences, though: With your code the player moves `sqrt(2)` times faster diagonally. Also, he does not move in a straight line towards the target. – Lucius Feb 02 '13 at 00:14