Learn Create Your Own Split Screen

Next Page

Now we'll add scoring. We'll definitely need a variable to keep track of the score:
var score = 0; // the score
And we'll display the score in the Do_a_Frame function. Remember the order we draw things on the canvas determines which ones are "in front of" the others, so we have control over whether fish can swim in front of the score or not.
ctx.fillStyle= "yellow"; ctx.font="15px Arial"; ctx.fillText("Score: " + score, 0, 20); // display score
We'll make use of the ImagesTouching function we introduced back in the bat game, and for every frame we'll loop through all the fish checking to see if the fish is touching the jelly. If it is, we'll remove the fish from the array, and bump the score by one.
for (var i=0; i < fish.length; i++) { // check every fish if (ImagesTouching(fish[i], jelly)) { // if it's touching the jelly fish.splice(i, 1); // remove the fish score = score + 1; // score goes up too } }
Come to think of it, we've ended up with hundreds of fish swimming yards either side of the screen. The fish that swim off-screen without being eaten just keep on swimming, further and further off-screen. You can't see them, but they're there. And for every frame we're processing the fish and checking for collision with the jelly. This will eventually slow things down, and it's also untidy.

As part of our "fish for-loop", we'll also see if the fish is way off-screen, and remove it from the array:

if (fish[i].x + fish[i].MyImg.width < 0 || fish[i].x > myCanvas.width) { fish.splice(i, 1); }