Phaser 3 - Set graphics object's anchor

2.6k Views Asked by At

I'm trying to set the anchor point of a rectangle graphics object to it's center so that I can tween it's rotation. The only related information that I can find says to use the dispalyOriginX and dispalyOriginY properties, but that doesn't seem to do anything. Here's my code:

export default class GameUi extends Phaser.GameObjects.Group {
  constructor(scene) {
    super(scene);

    let test = new Graphics(scene);
    test.setName('test');
    test.lineStyle(4, 0xffffff, 1);
    test.strokeRectShape(new Rectangle(100, 100, 75, 50));

    // The following doesn't work :(
    // test.displayOriginX = 0.5;
    // test.displayOriginY = 0.5;

    scene.tweens.add({
      targets: test,
      angle: 20,
      duration: 2000,
      ease: "Power2",
      yoyo: true,
      loop: -1
    });

    this.addMultiple([test], true);
  }
}

The rectangle is supposed to spin around its center, but as you can see in the image below, it seems to spin around the game area's top left corner. I tried the displayOrigin properties with values between 0.5 up to 500, all with the same result.

enter image description here

I was thinking it might be because I'm adding the rectangle to a group that's causing the issue, but I've tried not adding it to the group with the same effect. This is what my code looked like when it wasn't part of a group:

export default class GameUi {
  constructor(scene) {
    let test = scene.add.graphics();
    // the rest stays the same as in my first code example
  }
}
1

There are 1 best solutions below

0
exciteabletom On

I don't know what your Rectangle class is but I assume it's a extension of Phaser.graphics?

If so, you need to call thesetOrigin method on your rectangle instance.

tempRect = new Rectangle(100, 100, 75, 50) # create
tempRect.setOrigin(tempRect.halfWidth, tempRect.halfHeight) // Set origin to middle point

test.strokeRectShape(tempRect);