单击时让玩家移动到我的鼠标?

时间:2013-02-01 23:08:38

标签: java game-engine lwjgl

如何让我的播放器在点击时移动到鼠标(就像在魔兽中一样)?

到目前为止,我已经尝试过:

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

但如果我按下鼠标,那只能做我想要的。

1 个答案:

答案 0 :(得分:3)

只需存储最后一次点击的位置,让玩家朝那个方向移动。

将这些字段添加到您的播放器类:

int targetX;
int targetY;

在您的更新方法中存储新目标并应用移动:

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