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

Java 让玩家在单击鼠标时移动到我的鼠标?,java,game-engine,lwjgl,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 (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;
    }
} 
if(鼠标.isButtonDown(0)){
if(XMouse.getX()){
X-=速度;
}
如果(YMouse.getY()){
Y-=速度;
}
} 

但是,如果我按住鼠标,这只会满足我的需要。

只需存储最后一次单击的位置,并让玩家朝该方向移动即可

将以下字段添加到玩家类:

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

仅供参考,您可能需要谷歌“游戏引擎”。现在没有人从零开始编写游戏。您可能还想将其移动到gamedev stackexchange中。@gerrytan如果这是真的,您如何解释4000多个XNA问题?没有什么可以反对从头开始构建一个小游戏。对于较小的项目,游戏引擎通常是完全多余的。我用更新方法和你的方法替换了代码,并在顶部添加了2个变量,但没有work@griffy100我不会为你写游戏的,伙计。我修改了你的代码,使它简单了很多,而且很有效:
if(Mouse.isButtonDown(0)){TargetX=Mouse.getX();TargetY=Mouse.getY();}if(XTargetX){X-=Speed;}if(YTargetY){Y-=Speed;}
是的,也可以。不过,有两个区别:使用你的代码,玩家以对角线的速度移动
sqrt(2)
倍。此外,他也不会朝目标直线移动。