Scope issue with collision

I was coding, trying to input a game over, but when I test the code I get a scope error whenever I call up a different scene. Screenshot 2019-12-08 at 9.21.09 AM

(this is the original code)

this.physics.add.overlap(this.player,this.slimeE, function(player,slime){
		console.log('hit');
		if(slime.hostile){
			this.scene.start('menu');
		}
	});

i tried adding THIS to the end of the code but it still didnt work.

this.physics.add.overlap(this.player,this.slimeE, function(player,slime){
		console.log('hit');
		if(slime.hostile){
			this.scene.start('menu');
		}
	},this);

The function signature is as follows:
overlap(object1 [, object2] [, overlapCallback] [, processCallback] [, callbackContext])

You need to add the this as the fifth argument after adding the fourth argument with value null there after the callback function you passed. I guess, as I understand it is called processCallback. I tried to pull it out of docs, it is a bit confusing there imo.

this.physics.add.overlap(this.player,this.slimeE, function(player,slime){
		console.log('hit');
		if(slime.hostile){
			this.scene.start('menu');
		}
	}, null, this);

docs says for this processCallback here:

An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then collideCallback will only be called if this callback returns true .

and some same more here: Phaser 3 API Documentation - Class: World

It turns out it is useful. I mean it can cause to leaner tidier code, since it takes all the logic for the collision condition usually goes into the collideCallback in all examples I have ran across out of it. I will try to use it instead.

1 Like

thank you, it works now! :smiley:

:+1:
Need to activate this forum more.
We have a cool HTML5 game engine at the end even though I do not like the docs :slight_smile: