Learn Create Your Own Split Screen

Next Page

Obviously the bats are all falling in a line, but we want them to appear at random x-positions.

It'd be easy enough to add a line of code, but I'm going to do it by creating another method, just to show how our MySprite object can have lots of methods. In your own projects, you'll develop your objects with many, many methods so they become powerful subsystems in their own right.

Here's the new method. The calculation of the random x-position is the same as in the melon-catching game.

MySprite.prototype.GoRandomX = function() { this.x = Math.random() * (myCanvas.width - this.MyImg.width); // pick a random x-position, always fully visible }
To use it, we just call it in AddNewBat().

Even though the method is only a single line of code, making it part of the MySprite object means if we ever find something isn't quite right with that line of code, we only have to fix it in one place.