元画像なしでスプライトを生成する - Phaser3 Tips

元画像なしでスプライトを生成する #

 画像を用意せずにスプライトを生成する方法です。Phaser.GameObjects.Graphicsを使用します。

 まず、Phaser.GameObjects.Graphicsを生成します。

const graphics = this.add.graphics();

 次に、Phaser.GameObjects.Graphicsに描画を行います。ここでは、矩形を描画します。

graphics.fillStyle(0xffffff, 1); // 色を指定
graphics.fillRect(0, 0, 100, 100); // 矩形を描画

 最後に、Phaser.GameObjects.Graphicsを元にスプライトを生成します。

const sprite = this.add.sprite(0, 0, graphics.generateTexture()); // スプライトを生成
graphics.destroy(); // Graphicsを削除

完成例 #

const graphics = this.add.graphics(); // Graphicsを生成
graphics.fillStyle(0xffffff, 1); // 色を指定
graphics.fillRect(0, 0, 100, 100); // 矩形を描画
graphics.generateTexture("rect"); // Graphicsを元にテクスチャを生成
const sprite = this.add.sprite(0, 0, "rect"); // スプライトを生成
graphics.destroy(); // Graphicsを削除

完成例の解説 #

const graphics = this.add.graphics(); #

 Phaser.GameObjects.Graphicsを生成します。

graphics.fillStyle(0xffffff, 1); #

 色を指定します。fillStyleの第一引数に色を指定します。第二引数に透明度を指定します。透明度は0~1の間で指定します。

graphics.fillRect(0, 0, 100, 100); #

 矩形を描画します。fillRectの第一引数にX座標を指定します。第二引数にY座標を指定します。第三引数に幅を指定します。第四引数に高さを指定します。  矩形以外にも、円を描画するfillCircleや、線を描画するstrokeRectなどがあります。

graphics.generateTexture("rect"); #

 Phaser.GameObjects.Graphicsを元にテクスチャを生成します。generateTextureの第一引数にテクスチャのキーを指定します。

const sprite = this.add.sprite(0, 0, "rect"); #

 スプライトを生成します。spriteの第一引数にX座標を指定します。第二引数にY座標を指定します。第三引数にテクスチャのキーを指定します。

🄫wellwich.