Javascript 将玩家移动n个单位,使其靠近X点
我有一个播放器,看起来像这样:Javascript 将玩家移动n个单位,使其靠近X点,javascript,math,game-physics,Javascript,Math,Game Physics,我有一个播放器,看起来像这样: { 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.face.x,player.face.y),我可以使用什么公式沿鼠标的
{
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.face.x
,player.face.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);
鼠标的x和y应足以获得鼠标的方向mouse@sumeetkumar但我不知道怎么做。如果你认为你有一个想法,你能和我分享吗?我被这个问题难住了。由于某种原因,它仍然每次返回
null
。@eeze它的哪个部分返回null
?终点位置还是球员?显示完整代码,因为问题可能在其他地方。抱歉,您的代码没有问题。这是我的问题XD@eeze哈哈,没问题。
// 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);