Zoom Out Viewport based on Screen Size in PIXI.JS

161 views Asked by At

I am building a game using PIXI.js and it looks good on my desktop, but when playing on my phone, the FOV is really small making it so that I can barely see my surroundings. Likewise on large monitors, the user can see so much making it unfair.

Is there a way I can use the display window size to zoom out the camera so that it's fair for everyone to see the same surroundings?

1

There are 1 answers

0
Coder Gautam YT On

Answer found on this Github issue.

After reading the source code of pixi-viewport I came up with a solution that works well for my purposes. The following function will scale your stage and its contents to the target device window based on the supplied virtual resolution. The virtual resolution determines the scaling factor in pixels and the aspect ratio of the view, which will always remain the same regardless of the target device window dimensions. With center = true the global origin will be always in the middle of the screen.

function fit(center: boolean, stage: PIXI.Container, screenWidth: number, screenHeight: number, virtualWidth: number, virtualHeight: number) {
   stage.scale.x = screenWidth / virtualWidth
   stage.scale.y = screenHeight / virtualHeight

   if (stage.scale.x < stage.scale.y) {
       stage.scale.y = stage.scale.x
   } else {
       stage.scale.x = stage.scale.y
   }

   const virtualWidthInScreenPixels = virtualWidth * stage.scale.x
   const virtualHeightInScreenPixels = virtualHeight * stage.scale.y
   const centerXInScreenPixels = screenWidth * 0.5;
   const centerYInScreenPixels = screenHeight * 0.5;

   if (center) {
       stage.position.x = centerXInScreenPixels;
       stage.position.y = centerYInScreenPixels;
   } else {
       stage.position.x = centerXInScreenPixels - virtualWidthInScreenPixels * 0.5;
       stage.position.y = centerYInScreenPixels - virtualHeightInScreenPixels * 0.5;
   }
}

On your window resize function you can call it like this:

        window.onresize = () => {
            this.pixiInstance.renderer.resize(pixiDiv.clientWidth, pixiDiv.clientHeight)
            fit(true, this.pixiInstance.stage, pixiDiv.clientWidth, pixiDiv.clientHeight, this.virtual_w, this.virtual_h)
        }