devAR
devAR

Reputation: 458

Sprite location changes based on canvas size

my game has a dynamic width and height based on the users screen size. Im setting sprites at different locations on the map. The issue is that the sprites location will be off depending on the user screen size. So on my screen its fine but if I switch to a different screen, the sprites location will be off by a few pixels. How can I make it so that no matter the screen size, the sprites location is always in the same place. The following is my config

    const parentContainer = document.getElementById("feed-container");
    const canvasWidth = parentContainer.clientWidth;
    const canvasHeight = parentContainer.clientHeight;
    const config: Phaser.Types.Core.GameConfig = {
      type: Phaser.AUTO,
      width: canvasWidth,
      height: canvasHeight,
      // render: {
      //   pixelArt: true,
      //   antialias: true,
      // },
      parent: "phaser-container",
      physics: {
        default: "arcade",
        arcade: {
          gravity: { x: 0, y: 0 },
          fixedStep: false,
        },
      },
      scene: { preload: preload, create: create, update: update },
    };

example of how I'm currently positioning a sprite

      let tree = this.physics.add
          .sprite(500, 300, "tree")
          .setScale(0.5);

Upvotes: 0

Views: 43

Answers (1)

Coco
Coco

Reputation: 55

if you mean relative to the screen, you should use the code below

this.iw = window.innerWidth;
this.ih = window.innerHeight;

then use this code

      let tree = this.physics.add
          .sprite(500*this.iw, 300*this.ih, "tree")
          .setScale(0.5*(this.iw/this.ih));

Upvotes: 0

Related Questions