java - 单击时让播放器移动到我的鼠标?

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

但只有当我按住鼠标时,它才会执行我想要的操作。

最佳答案

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

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

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

关于java - 单击时让播放器移动到我的鼠标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14656616/

相关文章:

naming-conventions - "entity"和 "game object"之间有什么区别?

java - 如何让java使用毫米而不是像素?

java - 2D 游戏中的 LWJGL HUD

java - FBO 纹理显示全黑

java - 如何实现数组对称两列交换?

java - 在 ArrayList 中搜索字符串实例

android - 触摸时移除连续生成的 Sprite

java - Android AsyncTask 类中的 NullPointerException

java 小服务程序 : request parameter contains plus

oop - 模块化游戏引擎的例子?