Tween onComplete, this context is not GameScene anymore

In my Phaser 3 game, when the player loses I want it to display a game-over panel. I’ve added a rectangle (using graphics.fillRect) and add a tween to make it scale and fade in. Then when it has appeared, the scores and results are calculated and should also appear with different animations in the rectangle.

The problem is that when the onComplete function is called, it is called in the context of the Tween and not the GameScene. This gives error because I want to use Scene function like add.bitmaptext.

I’ve looked here but couldn’t find anything related. Is it possible to set the context of the onComplete function? See my code below

	checkGameOver: function() {
	
		// code..

		// show panel for gameover texts etc.
		var tw = this.tweens.add(
			{
				targets: this._gameoverpnl,
				scaleY: 1.0,
				alpha: 1.0,
				ease: 'Power3',
				duration: 1000, // duration of animation; higher=slower
				delay: 500,      // wait 500 ms before starting
				onComplete: this.showScoresResults  // set context? how?
			}
		);
	},

	showScoresResults: function() {

		// `this` is now the `Tween` not the `GameScene`, so add.bitmapText gives error
		var txt = this.add.bitmapText(100, 320, "fontwhite", "", 40); // <-- Error here
		
		// etc. code for results calcultation and animations..
	},

Use the bind function to set scope context.

Example:
onComplete: this.showScoresResults.bind(this)

2 Likes

You can also pass onCompleteScope.

Thanks for the tips, I used the .bind(this) and it works :slight_smile:

I couldn’t find anything on a onCompleteScope parameter or method, I looked here. Maybe you mean setCallback but how to use that as a onComplete callback? :confused:

onCompleteScope is a property you can pass to the tween’s configuration (i.e. the object you pass to this.tweens.add), which is a TweenBuilderConfig. Generally, setting the scope of a callback is cleaner than binding it because it does not create a new function. Memory implications aside, it also allows you to identify the function later, even though that’s rarely needed for a tween’s callback.