我有一个播放器,看起来像这样:

{
   x: [could be any integer],
   y: [could be any integer],
   facing: {
      x: [could be any integer],
      y: [could be any integer]
   }
}


假设播放器位于(player.xplayer.y),并且播放器面向鼠标方向(player.facing.xplayer.facing.y),那么我可以用来移动的公式是什么播放器在鼠标方向上的n个单位?

到目前为止,这是我尝试过的方法,但始终会导致null

var facingDistance = Math.sqrt(Math.pow(game.players[i].facing.x, 2) - Math.pow(game.players[i].x, 2));

game.players[i].x += (game.players[i].speed/facingDistance) *
(game.players[i].x - game.players[i].facing.x);

game.players[i].y += (game.players[i].speed/facingDistance) *
(game.players[i].y - game.players[i].facing.y);

最佳答案

// prefetch player object for cleaner code
var plr = game.players[i];

// normalized player direction
var facingDX = plr.facing.x - plr.x;
var facingDY = plr.facing.y - plr.y;
var facingLen = Math.sqrt(facingDX * facingDX + facingDY * facingDY);
facingDX /= facingLen;
facingDY /= facingLen;

// add n times this to position + round to integer coordinates
plr.x = Math.round(plr.x + facingDX * n);
plr.y = Math.round(plr.y + facingDY * n);

关于javascript - 将玩家移动n个单位,使其更接近X点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49909161/

10-12 14:10