Problem with isPlaying animation property in phaser 3

Viewed 45

I have a big problem with isPlaying property in Phaser 3 that causes a game block and an error in browser console. I have this two pieces of code in which I handle the collide between the missiles and the platforms of the game:

this.physics.add.collider(missile, platforms, () => {
                if (missile && (!missile.anims.isPlaying || missile.anims.currentAnim.key !== 'missExplosion')) {
                    missile.setTexture('expl1');
                    missile.play('missExplosion');
                    missile.on('animationcomplete',() => {
                        missile.destroy();
                    })
                }
                setTimeout(() => {
                    keyIsDown = true;
                }, 500);
            });

And this one :

this.physics.add.collider(cpuMissile, platforms, () => {
                  
                    if (cpuMissile && (!cpuMissile.anims.isPlaying || cpuMissile.anims.currentAnim.key !== 'cpuMissExplosion')) {
                        cpuMissile.setTexture('expl1');
                        cpuMissile.play('cpuMissExplosion');
                        
                        cpuMissile.on('animationcomplete',() => {
                            cpuMissile.destroy();
                        });
                        
                    }

                });

The two pieces of code are very similar, in fact they do the same animation, but the first on the projectile fired by player and the second on the projectile fired by cpu. Now the problem is that after some shot the game crash and in the console browser i have this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'isPlaying')

The problem indicates the two row with if-clause, but i don't understand what really cause the problem because the animation is fine for some repetitions, until the block of the game, even if I do nothing. I setup some setTimeout to prevent two animations on same sprite start in the same time, but it seem not depends on this. I hope the post is clearly, and thanks to everyone in advance!

1 Answers

You could simply add an extra check to both if - clauses, checking if the anims property exists, before accessing it, that should prevent running into the error.
(checking if properties exist, before accessing them, should always the way in javascript)

like this:

if (missile && missile.anins && (!missile.anims.isPlaying || missile.anims.currentAnim.key !== 'missExplosion')) {
...
              
if (cpuMissile && cpuMissile.anims &&(!cpuMissile.anims.isPlaying || cpuMissile.anims.currentAnim.key !== 'cpuMissExplosion')) { 
...

this should prevent the error from occurring, since isPlaying will only be checked, if the cpuMissile or missile object have the anims property. (There can be some occasions, where the object might not have it)

Related