我有一个播放器,看起来像这样:
{
x: [could be any integer],
y: [could be any integer],
facing: {
x: [could be any integer],
y: [could be any integer]
}
}
假设玩家处于(player.x
,player.y
),并且玩家面向鼠标方向,即(player.facing.x
,player.facing.y
) ,我可以使用什么公式将玩家移动到鼠标方向的单位?
这是我到目前为止所尝试的内容,但始终会产生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);
答案 0 :(得分:1)
// 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);