■画像を表示する
main.js
import Phaser from "phaser";
import GameScene from "./scenes/GameScene";
const config = {
type: Phaser.AUTO,
width: 600,
height: 300,
parent: 'game-container',
backgroundColor: '#ffffff',
scale: {
mode: Phaser.Scale.NONE,
autoCenter: Phaser.Scale.CENTER_BOTH
},
scene: [
GameScene
]
};
export default new Phaser.Game(config);
./src/objects/Block.js
export default class Block extends Phaser.GameObjects.Image {
constructor(scene, x, y) {
super(scene, x, y, 'black_block');
this.setOrigin(0.5); // 原点を中心にする
this.scene.add.existing(this); // シーンに追加する。
}
}
./src/scenes/GameScene.js
import { Scene } from 'phaser';
import Block from '../objects/Block.js'
export default class GameScene extends Phaser.Scene {
constructor() {
super('game');
}
preload() {
// 画像を読み込む
this.load.image("black_block", './assets/black.png');
}
create() {
// 画面中心に配置
var centerX = this.scale.width / 2;
var centerY = this.scale.height / 2;
var block = new Block(this, centerX, centerY);
}
update() {
}
}
■クリックイベント処理を追加
./src/objects/Block.js
export default class Block extends Phaser.GameObjects.Image {
constructor(scene, x, y) {
super(scene, x, y, 'black_block');
this.setOrigin(0.5); // 原点を中心にする
this.setInteractive(); // クリックやタッチを受け付ける
this.scene.add.existing(this); // シーンに追加する。
// クリックイベントの設定
this.on("pointerdown", this.handleClick, this);
}
handleClick(pointer, localX, localY, event) {
// 現在の位置をconsole.logに出力
console.log(`ClickX=${pointer.x}, Clicky=${pointer.y}\t画像内X=${localX}, 画像内Y=${localY}`);
}
}
■クリックイベント範囲を円型にする
./src/objects/Block.js
export default class Block extends Phaser.GameObjects.Image {
constructor(scene, x, y) {
super(scene, x, y, 'black_block');
this.setOrigin(0.5); // 原点を中心にする
// クリックやタッチを受け付ける
this.setInteractive(
new Phaser.Geom.Circle(this.width / 2, this.height / 2, this.width / 4),
Phaser.Geom.Circle.Contains
);
console.log(`画像の幅:${this.width} / 高さ:${this.height} 半径:${this.width / 4}`);
console.log(`配置位置X:${x} / Y:${y}`);
console.log(`範囲X:${x - this.width / 4} ~ ${x + this.width / 4}`);
this.scene.add.existing(this); // シーンに追加する
// クリックイベントの設定
this.on("pointerdown", this.handleClick, this);
}
handleClick(pointer, localX, localY, event) {
// 現在の位置をconsole.logに出力
console.log(`ClickX=${pointer.x}, Clicky=${pointer.y}\t画像内X=${localX}, 画像内Y=${localY}`);
}
}
■クリックイベントで自身を削除
export default class Block extends Phaser.GameObjects.Image {
constructor(scene, x, y) {
super(scene, x, y, 'black_block');
this.setOrigin(0.5); // 原点を中心にする
this.setInteractive(); // クリックやタッチを受け付ける
this.scene.add.existing(this); // シーンに追加する
// クリックイベントの設定
this.on("pointerdown", this.handleClick, this);
}
handleClick() {
// 削除
this.destroy();
}
}