Now we'll flesh out
set_random_side.
The first thing it does is pick a random number (in the range zero to just less than one). We choose a side depending on whether the random number is greater than 0.5, giving a 50:50 outcome. If we wanted more fish to come from one side, we could choose a different value.
Then it does a similar thing depending on the side:
- Position the fish so it's just off-screen, to the appropriate side
- Set a velocity in the appropriate direction, with some randomness as to how fast
- Possibly do a horizontal flip on the fish
I've cunningly made all my fish images
face left, so I know I have to
flip the ones heading right. If I hadn't made the raw images face all the same way, this would be a lot more untidy.
Finally we also set a y-position, being somewhere in the top 80% of the canvas.
function set_random_side (thing) {
if (Math.random() > 0.5) { // choose side 50:50
// start on LHS
thing.x = -thing.MyImg.width; // off-screen to the left
thing.velocity_x = Math.random()*8 + 2; // moving right
thing.flipH = true; // face other direction
}
else {
// start on RHS
thing.x = myCanvas.width; // off-screen to the right
thing.velocity_x = -1 * (Math.random()*8 + 2); // moving left
thing.flipH = false; // keep facing same way
}
thing.y = Math.random() * myCanvas.height * 0.8; // set a y-position
}