Learn Create Your Own Split Screen

Next Page

We're very nearly done. We just need to add some extra behaviours to the turtle.

Every frame, we'll check to see if the turtle is way off-screen but still has his visibility flag set. If so, we'll set a timeout to make him reappear a short random time from now, and set his invisibility flag to true so we don't keep rescheduling the timer.

if (turtle.x + turtle.MyImg.width < 0 || turtle.x > myCanvas.width) { // Turtle is off-screen if (turtle.visible) setTimeout(Appear_Turtle, Math.random()*3000); // Schedule the next turtle turtle.visible= false; }
In the for-loop where we think about every fish, we'll also check if the fish is touching the turtle. If it is, we'll just delete the fish -- the turtle has chomped the fish and it's no longer available to feed the jelly.
if (ImagesTouching(fish[i], turtle)) { fish.splice(i, 1); // The turtle ate a fish }
We'll also check whether the jelly is touching the turtle, and if so, deduct a big chunk of health. But not let the health go below zero. Further, we need to create a boolean variable so we only do this the first time we touch the turtle, otherwise we'll keep losing health every moment the turtle is passing by the jelly.
if (ImagesTouching(jelly, turtle) && !touched_turtle) { // Turtle is touching jelly (first time for this turtle) touched_turtle = true; // Only one health deduction per encounter health = health - 20; // Health goes down 20 if (health < 0) health = 0; // But never past zero }
We'll also add a background, and a test so if health ever drops to zero, we display a "game over" message.