ゲームオブジェクトに対するクリックに反応するコードの書き方
ゲーム開発コースではゲーム画面全体に対するクリックへのイベントハンドラの設定の方法を学習しました。 復習になりますがこれは以下のようなコードで実装できます。
this.input.on('pointerdown', (e)=>{
// pointerdownイベントが発生した時に実行されるコード
});
ゲーム画面に追加した図形やSpriteのことをまとめてゲームオブジェクトといいます。
個別のゲームオブジェクトに対するクリックへのイベントハンドラを設定することもできます。
手順は2ステップになります。
ステップ1: デフォルトではゲームオブジェクトに対するイベントハンドラの設定は無効になります。 setInteractive()
を呼び、イベントハンドラが設定できるようにします。
ステップ2: ゲームオブジェクトでon(イベント名, イベントハンドラ)
を呼び出す。
const create = function() {
this.circle = this.add.circle(100, 100, 50, 0xffffff);
this.circle.setInteractive();
this.circle.on('pointerdown', (e) => {
console.log(`x座標は${e.x}`);
console.log(`y座標は${e.y}`);
});
}
pointerdown
pointerup
pointermove
の3つのイベントは全て同様に実装することができます。
今回学習した内容を利用して、円をドラッグアンドドロップできるようにするコードを書くと次のようになります。
const create = function() {
this.circle = this.add.circle(100, 100, 50, 0xffffff);
this.circle.setInteractive();
this.holding = false;
this.circle.on('pointerdown', (e) => {
this.holding = true;
});
this.circle.on('pointermove', (e) => {
if (this.holding) {
this.circle.x = e.x;
this.circle.y = e.y;
}
});
this.circle.on('pointerup', (e) => {
this.holding = false;
});
};