user2023876
user2023876

Reputation:

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.

Upvotes: 1

Views: 1883

Answers (1)

Lucius
Lucius

Reputation: 3745

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;
}

Upvotes: 3

Related Questions