How to Move Player to Mouse Click or Tap in Phaser

Make a player.js module.

// Player
Player = function() {
  // we'll keep track of the player moving, since update() gets called on every frame
  this.isMoving = null;
};
Player.prototype = {
};

Here are some functions that will go into Player.prototype:

Initialize the player_walk sprite, which contains side-by-side frames of a player walking.

create: function() {
  // ... add player "this.sprite" to the game world ...
  // we've just started; don't let the player move yet
  this.isMoving = false;

  // walk animation
  this.sprite.loadTexture('player_walk', 0);
  this.sprite.animations.add('player_walk');

  // move character on input down/tap
  game.input.onDown.add(this.moveCharacter, this);
}

This is what happens when you click the screen with the mouse or tap on the screen.

moveCharacter: function(pointer) {
  // the player is moving now!
  this.isMoving = true;

  // 300 means 300 pixels per second. This is the speed the sprite will move at, regardless of the distance it has to travel.
  var duration = (game.physics.arcade.distanceToPointer(this.sprite, pointer) / 300) * 1000;

  // pointer.x and pointer.y are the input x and y values coming from the mouse click or tap.
  tween = game.add.tween(this.sprite).to({ x: pointer.x, y: pointer.y }, duration, Phaser.Easing.Linear.None, true);

  // once tween is completed, call moveCharacterComplete()
  tween.onComplete.add(this.moveCharacterComplete, this);
}

Let’s stop the player from walking once he’s reached his destination.

moveCharacterComplete: function() {
  this.isMoving = false;
  this.sprite.animations.stop();
}

This gets called on every frame.

update: function() {
  if (this.isMoving) {
    // play sprite at 12 frames per second
    this.sprite.animations.play('player_walk', 12, true);
  } else {
    this.sprite.animations.stop();
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *