Get Swipe Direction (スワイプ方向判定)
ユーザーの入力スワイプ(ドラッグ)操作の方向を判定するヘルパーメソッドです。
pointerup イベントなどで呼び出すことで、フリック操作やスワイプ操作の実装に利用できます。
画面上をドラッグ(スワイプ)して離すと、方向が表示されます。
コードスニペット
Section titled “コードスニペット”1. メソッド (Method)
Section titled “1. メソッド (Method)”シーンクラスに追加する判定メソッドです。
/** * ポインターの移動量からスワイプ方向を判定する * @param pointer Phaserのポインターオブジェクト * @param threshold スワイプとみなす最小距離 (デフォルト: 30px) * @returns 'UP', 'DOWN', 'LEFT', 'RIGHT', または null (判定不能/タップ) */public getSwipeDirection(pointer: Phaser.Input.Pointer, threshold: number = 30): string | null { const dx = pointer.upX - pointer.downX; const dy = pointer.upY - pointer.downY;
// 移動量が閾値未満ならスワイプとみなさない if (Math.abs(dx) < threshold && Math.abs(dy) < threshold) { return null; }
// 水平方向と垂直方向の移動量を比較 if (Math.abs(dx) > Math.abs(dy)) { return dx > 0 ? 'RIGHT' : 'LEFT'; } else { return dy > 0 ? 'DOWN' : 'UP'; }}2. 使い方 (Usage)
Section titled “2. 使い方 (Usage)”create メソッドなどで入力イベントのリスナーを設定し、そこで呼び出します。
create() { this.input.on('pointerup', (pointer: Phaser.Input.Pointer) => { const direction = this.getSwipeDirection(pointer);
if (direction) { console.log(`Swipe Direction: ${direction}`); // スワイプ時の処理... } });}完全なソースコード
Section titled “完全なソースコード”クラス全体を見る
import Phaser from 'phaser';
export class GetSwipeDirectionScene extends Phaser.Scene { private resultText: Phaser.GameObjects.Text | undefined;
constructor() { super({ key: 'GetSwipeDirectionScene' }); }
create() { this.add.text(10, 10, 'Swipe Direction Demo', { fontFamily: '"Noto Sans JP", sans-serif', fontSize: '24px', color: '#00ff00' });
this.add.text(400, 200, '画面をスワイプ', { fontFamily: '"Noto Sans JP", sans-serif', fontSize: '20px', color: '#ffffff' }).setOrigin(0.5);
this.resultText = this.add.text(400, 300, '', { fontFamily: '"Noto Sans JP", sans-serif', fontSize: '48px', color: '#ffff00', fontStyle: 'bold' }).setOrigin(0.5);
// 入力イベントのリスナーを設定 this.input.on('pointerup', (pointer: Phaser.Input.Pointer) => { const direction = this.getSwipeDirection(pointer);
if (direction) { this.resultText?.setText(`Direction: ${direction}`); } else { this.resultText?.setText('Tap (No Swipe)'); } }); }
/** * ポインターの移動量からスワイプ方向を判定する * @param pointer Phaserのポインターオブジェクト * @param threshold スワイプとみなす最小距離 (デフォルト: 30px) * @returns 'UP', 'DOWN', 'LEFT', 'RIGHT', または null (判定不能/タップ) */ public getSwipeDirection(pointer: Phaser.Input.Pointer, threshold: number = 30): string | null { const dx = pointer.upX - pointer.downX; const dy = pointer.upY - pointer.downY;
if (Math.abs(dx) < threshold && Math.abs(dy) < threshold) { return null; }
if (Math.abs(dx) > Math.abs(dy)) { return dx > 0 ? 'RIGHT' : 'LEFT'; } else { return dy > 0 ? 'DOWN' : 'UP'; } }}実装のポイント
Section titled “実装のポイント”-
threshold(閾値) の設定: 指が少し動いただけでもスワイプと判定されないよう、thresholdで最小移動距離を設定しています。ゲームの性質に合わせて調整してください。 -
pointerupでの判定: この実装では指を離した瞬間 (pointerup) に判定を行っています。リアルタイムな判定が必要な場合はpointermoveイベントを利用し、pointer.downXからの距離を都度計算する必要があります。 -
対角線の判定: このロジックは4方向(上下左右)のみを判定します。斜め入力も判定したい場合は、角度 (
Math.atan2) を使用して8方向などに分岐させる必要があります。