Instantly share code, notes, and snippets.

Embed
What would you like to do?
Let's Make a Game: Invaders - Bug Fix
/**
* The Bug:
* We told Phaser to create 30 explosions, which isn't enough. There are two game conditions: either
* all 30 invaders are destroyed, or the player is hit 3 times. If the player destroys 29 invaders,
* there is only 1 explosion left in the collection. If the player is hit, that leaves 0. If the
* player is hit again, the game freezes.
*
* How to Reproduce:
* - Start the game.
* - Kill 29 alien invaders.
* - Allow the last one to kill you.
* - The game will freeze after the second alien bullet hits the player.
*
* How to Fix:
* - Update handleCreate with a bigger quantity of possible explosions.
* - Add a check to the handleCollision function to ensure a valid explosion reference.
*/
// ORIGINAL ERRONEOUS CODE:
function handleCreate() {
// ... omitted for brevity ...
// Create some explosions!
explosions = this.add.group({
defaultKey: 'kaboom',
maxSize: 30
});
// ... omitted for brevity ...
}
// CORRECTED CODE, PART 1:
function handleCreate() {
// ... omitted for brevity ...
// Create some explosions!
explosions = this.add.group({
defaultKey: 'kaboom',
maxSize: 32
});
// ... omitted for brevity ...
}
// CORRECTED CODE, PART 2:
function handleCollision( target, bullet ) {
// If both the target and bullet are active.
if ( target.active === true && bullet.active === true ) {
// ... omitted for brevity ...
// Get the first explosion, and activate it.
var explosion = explosions.get();
// If we have a valid explosion...
if ( explosion ) {
explosion.setActive( true );
// Place the explosion on the screen, and play the animation.
explosion.setOrigin( 0.5, 0.5 );
explosion.x = target.x;
explosion.y = target.y;
explosion.play( 'explode' );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment