Caesar Krit
Caesar Krit

Reputation: 214

Phaser scrolling background

My goal is to make a sprite bigger than the screen and have the user scroll to see the different parts of it, so I wanted to ask if Phaser had any sprite eventListener-functions such as:

    var canvas = window.document.getElementsByTagName('canvas')[0],
        prevX = 0, prevY = 0, mouseDown = false;

where canvas can be used as

    canvas.addEventListener('mousedown',function(e){
    });

   canvas.addEventListener('mousemove',function(e){
    });

Upvotes: 1

Views: 2314

Answers (2)

jdnichollsc
jdnichollsc

Reputation: 1569

If using the camera is OK for you, you can try this Phaser 2 plugin: https://jdnichollsc.github.io/Phaser-Kinetic-Scrolling-Plugin/

With this plugin you can enable vertical and horizontal scroll to simulate scrolling into the canvas element used by Phaser, also you can customize the movement before to initialize the plugin, example:

var game = new Phaser.Game(400, 400, Phaser.AUTO, '', {
  init: function () {

    //Load the plugin
    this.game.kineticScrolling = this.game.plugins.add(Phaser.Plugin.KineticScrolling);
  },
  create: function () {

    //Configure the plugin
    this.game.kineticScrolling.configure({
      kineticMovement: true,
      timeConstantScroll: 325, //really mimic iOS
      horizontalScroll: true,
      verticalScroll: false,
      horizontalWheel: true,
      verticalWheel: false,
      deltaWheel: 40
    });

    //Starts the plugin
    this.game.kineticScrolling.start();

    //Changing the world size
    this.game.world.setBounds(0, 0, 800, 800);
  },
  stopScrolling: function () {
    //Stop the plugin
    this.game.kineticScrolling.stop();
  }
});

Also there's a fork for Phaser 3, check the repo from GitHub.

Regards, Nicholls

Upvotes: 1

Caesar Krit
Caesar Krit

Reputation: 214

Here is how I did it.

In your update function:

if (this.game.input.activePointer.isDown) { 
  if (this.game.origDragPoint) {    
    // move the camera by the amount the mouse has moved since last update
    this.game.camera.x += this.game.origDragPoint.x - this.game.input.activePointer.position.x;
    this.game.camera.y += this.game.origDragPoint.y - this.game.input.activePointer.position.y;
  }
  // set new drag origin to current position
  this.game.origDragPoint = this.game.input.activePointer.position.clone();
}
else {
  this.game.origDragPoint = null;
}

Upvotes: 3

Related Questions