16

I'm making a game in Phaser using some large images that I want to scale down in the actual game:

create() {
    //Create the sprite group and scale it down to 30%
    this.pieces = this.add.group(undefined, "pieces", true);
    this.pieces.scale.x = 0.3;
    this.pieces.scale.y = 0.3;

    //Add the players to the middle of the stage and add them to the 'pieces' group
    var middle = new Phaser.Point( game.stage.width/2, game.stage.height/2);
    var player_two = this.add.sprite(middle.x - 50, middle.y, 'image1', undefined, this.pieces);
    var player_one = this.add.sprite(middle.x, middle.y-50, 'image2', undefined, this.pieces);
}

However because the sprites are scaled in size, their starting location is also scaled, so instead appearing in the middle of the stage, they appear only 30% of the distance to the middle.

How do I scale the sprite image without it affecting their location?

(The code is incidentally in Typescript but I think this particular sample is also javascript so that's probably irrelevant)

Migwell
  • 18,631
  • 21
  • 91
  • 160

3 Answers3

11

Set Sprite.anchor to 0.5 so the physics body is centered on the Sprite, scale the sprite image without it affecting their location.

this.image.anchor.setTo(0.5, 0.5);
tomcask
  • 171
  • 6
9

You can scale your sprite like so:

var scaleX = 2;
var scaleY = 2;    
sprite.scale.set(scaleX, scaleY);

then calculate position of sprite:

 var positionX = 100;
 var positionY = 100;

 sprite.x = positionX / scaleX;
 sprite.y = positionY / scaleY;

Now your sprite is at position (100, 100). The problem is that sprite.x got multiplied by with scaleX.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Koks_rs
  • 619
  • 1
  • 7
  • 25
1

Regarding Phaser, I'd like to add that in the specific case of weapon.bullets or other groups you create yourself you're going to have to do it this way instead:

weapon.bullets.setAll('scale.x', 0.5);
weapon.bullets.setAll('scale.y', 0.5);

I got stuck on this and ended up in this thread, which is closed but in my case just not what I needed. Others will hopefully have some use out of this :)

Dwad
  • 165
  • 1
  • 7
Dirk
  • 23
  • 2