`graphics` 对象本身运行良好,但不适用于 `Phaser.Display.Align.In.Center`,我错过了什么?

A `graphics` object works well by itself but doesn't work with `Phaser.Display.Align.In.Center`, what am I missing?

我正在尝试将给定矩形中的圆居中。完成这项工作的方法之一可能是 graphicsPhaser.Display.Align.In.Center 一起工作,我在这样做时遇到了麻烦。这是代码。

class BootScene extends Phaser.Scene {
  constructor() {
    super({
      key: 'BootScene'
    });
  }
  create() {
    let btn = this.add.rectangle(800, 600, 200, 150, '#000').setOrigin(1);
    let txt = this.add.text(0, 0, 'click');
    Phaser.Display.Align.In.Center(txt, btn, );

    let graphics = this.add.graphics({
      x: 750,
      y: 550
    });
    var shape = new Phaser.Geom.Circle(0, 0, 24);
    graphics.fillStyle(0xff0000, 1);
    graphics.fillCircleShape(shape);
    //Phaser.Display.Align.In.Center(graphics, btn);
  }
}

var config = {
  width: 800,
  height: 600,
  backgroundColor: '#555',
  scene: [BootScene]
}

var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>

上面的代码中有 3 个可视部分:btn 矩形、txt 文本和 graphics.

Phaser.Display.Align.In.Center 适用于 btntxt

graphics 使用

btn 配合使用效果很好
this.add.graphics({
      x: 750,
      y: 550
    });

但是,如果我取消注释下面的行

Phaser.Display.Align.In.Center(graphics, btn);

graphics 不见了,不管我将配置设置为 { x: 750, y: 550 } 还是 { x: 0, y: 0 }

我错过了什么?


我知道我可以使用类似

的东西
let circle2 = this.add.circle(0, 0, 32, 0xf00000);
Phaser.Display.Align.In.Center(btn_circle, circle2);

我只是想知道为什么当我将 graphicsPhaser.Display.Align.In.Center 组合在一起时它不起作用。

Update: it seems to be a bug of phaser (or a mistake in the documentation), since after calling Phaser.Display.Align.In.Center on the graphics object, the x and y properties are set to NaN, and acording the documenation Align should accept a GameObject, which the Graphics object is.

这是一个可能的解决方案:

  • 您可以简单地从 graphics 对象生成纹理,在 graphics 对象
  • 上使用函数 generateTexture
  • 将新创建的图像与btn
  • 对齐
  • 我刚刚添加了对 txt 对象的 setDepth 调用,因此它是可见的

class BootScene extends Phaser.Scene {
  constructor() {
    super({
      key: 'BootScene'
    });
  }
  create() {
    let btn = this.add.rectangle(300, 175, 200, 150, '#000').setOrigin(1);
    let txt = this.add.text(0, 0, 'click');
    Phaser.Display.Align.In.Center(txt, btn );

    let graphics = this.make.graphics({
      x: 24,
      y: 24,
    });
    var shape = new Phaser.Geom.Circle(24, 24, 24);
    graphics.fillStyle(0xff0000, 1);
    graphics.fillCircleShape(shape);
        
    graphics.generateTexture('gCircle', 48, 48);
    let image = this.add.image(200, 200, 'gCircle');
    Phaser.Display.Align.In.Center(image, btn);

    // only to make the Button visible
    txt.setDepth(2);
            
  }
}

var config = {
  width: 400,
  height: 200,
  backgroundColor: '#555',
  scene: [BootScene]
}

var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>