Learn Create Your Own Split Screen

Next Page

Let's flesh out the add_a_random_fish function.

I happen to have images of four different fish, and they all have file names such as "fish1.png", "fish2.png", etc. We'll be able to generate a random file name from "fish1.png" to "fish4.png".

The images are all slightly different sizes, but that doesn't matter because our code has been written so the sprites use the size of whatever image they're given, and there's no actual numbers hard-coded anywhere.

We want to start some fish on the left, travelling right, and some the other way around. For clarity, I'm splitting that off into a separate function called set_random_side(), and we'll flesh that out next.

Finally, we push the new fish into the fish array.

function add_a_random_fish() { var which_fish= Math.floor(Math.random()*4)+1; // random number, 1 to 4 var new_fish = new MySprite("http://s2js.com/img/etc/fish" + which_fish + ".png"); // new sprite with random fish image set_random_side(new_fish); // position the fish fish.push(new_fish); // add it to the array }