Trying to get mouse wheel zoom effect in Phaser

Viewed 1480

Zoom in and out with the mouse wheel seem to be working. However I want to the throw the mouse position in the mix.

If the user zooms in, the camera would (preferably slowly, but instantly would work also) move towards the mouse position as the as it zooms in or out. In other words the camera should center on the current mouse x,y coords or steer towards it at least, while zooming.

Does the camera x,y not equal canvas x,y? It seems to pan in the opposite direction. I've tried both pan() and centerOn() in my [Typescript] create() method:

this.input.on("wheel",  (pointer, gameObjects, deltaX, deltaY, deltaZ) => {

  if (deltaY > 0) {
    this.camera.zoom -= .1;
  }

  if (deltaY < 0) {
    this.camera.zoom += .1;
  }

  this.camera.pan(pointer.x, point.y, 2000, "Power2");

  //this.camera.centerOn(pointer.x, pointer.y);

});

This is a longshot, but I'd like to mimic the zoom behavior in the game Distant Worlds.

2 Answers

Too late for the OP, but might be useful for other people. I found a way to make the camera work in a way similar to games like Distant Worlds.

     this.input.on("wheel",  (pointer, gameObjects, deltaX, deltaY, deltaZ) => {

        if (deltaY > 0) {
            var newZoom = this.camera.zoom -.1;
            if (newZoom > 0.3) {
                this.camera.zoom = newZoom;     
            }
        }
      
        if (deltaY < 0) {
            var newZoom = this.camera.zoom +.1;
            if (newZoom < 1.3) {
                this.camera.zoom = newZoom;     
            }
        }

        // this.camera.centerOn(pointer.worldX, pointer.worldY);
        // this.camera.pan(pointer.worldX, pointer.worldY, 2000, "Power2");
      
      });

    this.input.on('pointermove', (pointer) => {
        if (!pointer.isDown) return;

        this.camera.scrollX -= (pointer.x - pointer.prevPosition.x) / this.camera.zoom;
        this.camera.scrollY -= (pointer.y - pointer.prevPosition.y) / this.camera.zoom;
    });

https://photonstorm.github.io/phaser3-docs/Phaser.Input.Pointer.html#worldX__anchor

The x, y of pointer are relative to the top-left of what you can see, it doesn’t take into consideration the current camera position. worldX and worldY, when passed in an event like the one above, are offset with the camera position. So calling camera.pan(worldX, worldY) will center the camera on what you are hovering over.

Here’s a slightly different example with clicking. https://stackblitz.com/edit/so-phaser-pan-to-mouse

Related