Finally, no game would be complete without a user interface to display the player's score and health. In order to do this we will need to adjust the game frameworks draw
method to allow text to be drawn to the canvas as well as introduction a number of variables which monitor and update the player's score and health.
To begin with, we will introduce two new variables that hold the player's score and health at the top of the
Main
object.var score = 0; var health = 100;
Next, we will draw the user interface elements to the screen, these elements are used to represent the player's score and health. Inside of the object manager 's
Draw
function place the following code before thedrawImage
function call:this.context.font = "30px Arial"; this.context.fillText("Score: " + score, 15, 50); this.context.fillText("Health: " + health, 625, 50);
Inside of the
Enemy
object'sUpdate
function, we will decrement the player's health each time they collide with an enemy. To do this update the collision detection check with the following:if(this.BoundingBox().Intersects(player.BoundingBox())) { this.DisposeEnemy(); health -= 14; }
We will also need to increase the player's score each time they collect a pickup. Therefore in order to do this we will need to update the collision detection check within the
Pickup
object with the following:if(this.BoundingBox().Intersects(player.BoundingBox())) { this.DisposePickup(); effect.play(); score++; }
Once you have completed these final steps, your game should look something similar to the following screenshot:
We begin by creating two variables that are responsible for holding the player's score and their health.
The values of these variables are then drawn to the canvas through the use of string concatenation and the HTML5's fillText
function that outputs text, with no effects applied to it, to the canvas.
Both of the score and health values are updated inside of either the Enemy
or Pickup Update
functions. The score value is incremented by one each time the player collides with a collectible object. Similarly the health value is decremented each time the player collides with an enemy object. Each of these values is updated in real time and the player's results are reflected on the canvas.
Finally, we perform a check to see if the player has collided with a pickup, that is, a berry, and if they have we play our sound effect and increment the score.