Mouse click on image cannot access scene (this)

Hi,

When there is a mouse click on the image, on the console there is an error as below. I think it means “this.” is not accessible. I have no idea how this happens. Any idea?

Generally, if I want to open a popup window for me to show texts messages, how can I do this with Phaser 3? I saw examples for Phaser 3, but could not find the similar with Phaser 3.

Can anyone help me?

(The error message is below)
Uncaught TypeError: Cannot read properties of undefined (reading ‘setText’)
at Image. (part22.php:44:16)
at Image.emit (phaser.js:1909:35)
at InputPlugin.processDownEvents (phaser.js:186075:24)
at InputPlugin.update (phaser.js:185806:35)
at InputManager.updateInputPlugins (phaser.js:93090:47)
at InputManager.onMouseDown (phaser.js:93276:14)
at HTMLCanvasElement.onMouseDown (phaser.js:94478:25)

(The source codes is below)

<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>Sum 100</title>
    <script src="//cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

<script>

var config = {
    type: Phaser.AUTO,
    width: 780,
    height: 540,
    parent: 'phaser-example',
    pixelArt: true,
    backgroundColor: '#F00000',
    scene: {
        preload: preload,
        create: create
    }
};

var game = new Phaser.Game(config);

function preload ()
{
    this.load.bitmapFont('atari', 'assets/fonts/bitmap/atari-smooth.png', 'assets/fonts/bitmap/atari-smooth.xml');
    this.load.image('info', 'assets/info_64x64.png');
}

function create ()
{
var info_image = this.add.image(680,510,'info').setInteractive({cursor: 'pointer'});

this.text5 = this.add.bitmapText(560, 100, 'atari', 'Hello', 20).setAlpha(1);  // this works fine.
this.text5.setText("hi");  // this works fine, too.

info_image.on('pointerdown', function () {
    this.text5.setText("greeings");    // this causes error
});

}
</script>

you forgot to use the callbackscope “this”.

info_image.on(‘pointerdown’, function () {
this.text5.setText(“greeings”);
},this);

1 Like

Hi NRJ, thanks for your great help! It solved the issue perfectly. :grinning: :grinning: :grinning: