【问题标题】:Making a player move to my mouse when clicked?单击时让玩家移动到我的鼠标?
【发布时间】:2013-02-01 23:08:37
【问题描述】:

如何让我的玩家在点击鼠标时移动到鼠标上(就像在魔兽争霸中一样)?

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

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

但这只有在我按住鼠标时才能达到我想要的效果。

【问题讨论】:

  • 仅供参考,您可能需要谷歌搜索“游戏引擎”。这些天没有人从头开始编写游戏。
  • 您可能还想将其移至 gamedev stackexchange。
  • @gerrytan 如果这是真的,那么您如何在 SO 上解释 超过 4000 个 XNA 问题?从头开始构建一个小游戏没有什么好说的。对于较小的项目来说,游戏引擎通常是完全矫枉过正的。

标签: java game-engine lwjgl


【解决方案1】:

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

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

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

【讨论】:

  • 我用你的替换了更新方法中的代码,并在顶部添加了 2 个变量,但它不起作用
  • @griffy100 我不会为你写游戏的,伙计。
  • 我修改了你的代码,让它变得更简单,而且它工作正常:if(Mouse.isButtonDown(0)){ TargetX=Mouse.getX(); TargetY=Mouse.getY(); } if(X&lt;TargetX){X+=Speed;} if(X&gt;TargetX){X-=Speed;} if(Y&lt;TargetY){Y+=Speed;} if(Y&gt;TargetY){Y-=Speed;}
  • 是的,也可以。但是有两个区别:使用您的代码,玩家在对角线上移动 sqrt(2) 倍。此外,他不会朝着目标直线移动。
猜你喜欢
  • 2022-06-10
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多