将玩家移近 X 点 n 个单位
Move a player n units closer to point X
我有一个播放器,它看起来像这样:
{
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
), 我可以使用什么公式将玩家沿鼠标方向移动 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);
我有一个播放器,它看起来像这样:
{
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
), 我可以使用什么公式将玩家沿鼠标方向移动 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);