This is the fourth part of HTML5 Game Development with Phaser2. The first three parts show you how to set up a game container, import the Phaser library, create a new game object, and display sprites, define character animation, enable physics system and create a sprite group.

In this part, we will show the update function. The update function lets you build your game logic. The game will update on the fly, complying with the logics in the update function. The logic can include collision detection and animation.


1. Collision processing

To kill the star in the group stars when the player collides with a star,

 game.physics.arcade.overlap(player, stars, collectStar, null, this);

The first two names are the objects to be examined for collision.

The third name is the callback function to be executed once collision takes place.

The fourth value is the additional callback function. If it is null, there is no additional check.

The last value, this, says that the current game context is the place where the callback function will run.

Callback function: collectStar

The following is an example of the callback collectStar

function collectStar(player, star){
    star.kill();
    score = score + 10;
    scoreText.text = 'Score: ' + score;

}

2. Hot key actions

In the Part 3, four hot keyboard keys are defined in the create function:

var cursors = game.input.keyboard.createCursorKeys();

In the update function, we can define the actions associated with the hot keys, including the moving speed of the player, animation to be applied, frame change of sprite and so on.

	if (cursors.left.isDown) {
		player.body.velocity.x = -150;
        player.animations.play('left');
	} else if (cursors.right.isDown) {
		player.body.velocity.x = 150;
        player.animations.play('right');
	} else {
		player.body.velocity.x = 0;
        player.frame = 4;
	} 

	if (cursors.up.isDown) {
		player.body.velocity.y = -300;
	}