phaserで、オブジェクトを生成し、クリックイベントに関数を指定しておき
その関数から、インスタンス変数にアクセスしようとした場合

export class xxxxxx {
    constructor(scene, rnd) {
        this.scene = scene;
        this.data = [];
    }

    init(){
        // オブジェクト生成
       this.#createObject();

        // データ生成(略)
        this.createData(); // ここでthis.dataにデータを追加する
    }

    #createObject(){
        // オブジェクトを生成(実際はもっとちゃんといろいろ設定している)
        const obj = this.scene.add.rectangle(100, 100, 100, 100, 0x000000, 0); //透明なクリック検知プレート
        obj.setInteractive();
        obj.on("pointerdown", this.#clickAreaClick);
    }

    #clickAreaClick(pointer, localX, localY){
        console.log(this.data); // undefined
    }
}

#clickAreaClickメソッドがイベントハンドラとして登録されると、
そのメソッド内でのthisは、initインスタンスを参照せず、
イベントのターゲット(この場合はclickArea)を参照します。
そのため、this.tileDataがundefinedになります。

解決策(アロー関数を使用)

obj.on("pointerdown", (pointer, localX, localY) => {
    this.#clickAreaClick(pointer, localX, localY); 
});

解決策(bindメソッドを使用)

obj.on("pointerdown", this.#clickAreaClick.bind(this));
投稿日時: 2024-08-04 10:42:04

./src/main.js

import Phaser from "phaser";
import GameScene from "./scenes/GameScene";

const config = {
    type: Phaser.AUTO,
    width: 400,
    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/scenes/GameScene.js

import { Scene } from 'phaser';
import Rect from '../objects/Rect'

export default class GameScene extends Phaser.Scene {

    constructor() {
        super('GameScene');
    }

    create() {
        const rect = new Rect(this, 100, 200);
    }
}

./src/objects/Rect.js

export default class Rect {
    constructor(scene, x, y) {
        const centerX = scene.scale.width / 2;
        const centerY = scene.scale.height / 2;
        const width = 200;
        const height = 200;

        const clickArea = scene.add.rectangle(centerX, centerY, width, height, 0x000000, 0); // 透明な矩形
        clickArea.setDepth(30);

        clickArea.setInteractive();
        clickArea.on("pointerdown", this.handleClick);
        scene.add.existing(clickArea);
    }

    handleClick(pointer, localX, localY) {
        console.log(`ClickX=${pointer.x}, Clicky=${pointer.y}\t画像内X=${localX}, 画像内Y=${localY}`);
    }
}
投稿日時: 2024-08-04 06:51:04
F#

普段使わない言語でプログラムの問題を解いて遊ぶときの確認用メモ

F#

open System;
let a:String array=Console.ReadLine().Split(' ')
投稿日時: 2024-08-03 03:58:03

最近の投稿

最近のコメント

タグ

アーカイブ

その他