Search code examples
javascriptmathgame-physics

Move a player n units closer to point X


I have a player, which looks like this:

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

Assuming the player is at (player.x, player.y), and the player is facing in the direction of the mouse, which is at (player.facing.x, player.facing.y), what is a formula that I could use to move the player n units in the direction of the mouse?

Here is what I've tried so far, but it always results in 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);

Solution

  • // 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);