如何在Phaser 3中为整个容器创建掩模?



我正在尝试创建一个具有背景,球体阴影和遮罩的行星,在Phaser 2中实现这一点非常简单,但现在它对我来说有一堆棘手的部分

一旦我更新了容器的mask属性,什么都没有显示。我已经尝试了几个mask组,但都没有成功…

换句话说:我需要"使用圆形蒙版

将矩形背景置入球体内我做错了什么?也许还有其他更好的方法吗?

这是我使用的方法:

init({ x, y, size, sprite, id }) {
const container = this.scene.add.container(x, y);
const width = (1200 / 300) * 200;
const height = 200;
const earthBMD = this.scene.textures.createCanvas(`earthBMD${id}`, width, height);
earthBMD.draw(0, 0, this.scene.textures.get(`map-${size}-${sprite}`).getSourceImage());
const planet = this.scene.add.sprite(0, 0, earthBMD).setOrigin(0.5).setAngle(-15);
const shadow = this.scene.add.sprite(0, 0, 'sphere').setOrigin(0.5, 0.5).setScale(0.5);
const mask = this.scene.make.graphics(0, 0).fillStyle(1000000, 0.5).fillCircle(0, 0, 150);
container.add([planet, mask, shadow]);
container.mask = new Phaser.Display.Masks.GeometryMask(this.scene, mask);
return container;
}

应该很容易创建所需的效果(至少使用这个基本的GameObjects)。我不确定init函数在哪里。如果它是在一个场景中,你只需要从this.scene....中移除scene,它应该工作。(这将是重点问题)

注:不要将mask添加到容器中,就像这行container.add([planet, mask, shadow]);一样,除非你想在canvas上渲染蒙版图像/形状。

这里是一个简化的例子:

document.body.style = 'margin:0;';
var config = {
type: Phaser.CANVAS,
width: 536,
height: 183,
scene: {
create
},
banner: false
}; 
function create () {
const container = this.add.container(0, 0);
const width = config.width;
const height = config.height;
let g = this.make.graphics({add:false});

g.fillStyle(0xffff00)
g.fillRect(10,10, 150, 150);

g.generateTexture('map', 150, 150);

const planet = this.add.sprite(50, 10, 'map')
.setOrigin(0)
const mask = this.make.graphics({add:false})
.fillStyle(1000000, 0.5)
.fillCircle(0, 0, 200);

container.add([planet]);
container.mask = new Phaser.Display.Masks.GeometryMask(this, mask);
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>

注。官方的例子很好。查看这些示例

最新更新