We're
not going to use a MySprite for this -- we're just going to use an
Image and use
drawImage to place it where we want.
First, we create the variable and load it up:
var bottom_bar = new Image();
bottom_bar.src = "http://s2js.com/img/etc/flappybottom.png" ;
Remember it's just a plain-old Image, not a fancy MySprite, so it doesn't know how to move itself, display itself, or anything really.
Then we'll create a function that will get called once every frame.
function display_bar_running_along_bottom() {
bottom_bar_offset = bottom_bar_offset + pipe_speed;
if (bottom_bar_offset < -23) bottom_bar_offset = 0;
ctx.drawImage(bottom_bar, bottom_bar_offset, myCanvas.height - bottom_bar.height);
}
drawImage draws the stripe at the bottom of the canvas, with an
x-position of bottom_bar_offset which is
initially zero.
Each frame, we adjust bottom_bar_offset by the pipe speed (which is a negative number which makes things move to the left). This means that each frame, the stripe is drawn further and further left.
The if-statement is the bit that makes it all work. Once the stripe is -23 pixels to the left, we reset it back to zero.
Because the image repeats itself every 24 pixels, this creates the illusion of continuous movement.
There's just one little "gotcha" -- we only want the bar to move when the game is in running mode. We want it visible all the time, but only moving when running. We can achieve this, perhaps inelegantly, by moving the line that changes the bottom_bar_offset variable to be within the appropriate case of the frame rendered. You'll see that on the next page.
You might be thinking, "hang on, if it repeats every 24 pixels, why do we reset when the offset gets to zero?!". The reason is, the offset starts at zero. There's no difference between counting from 1 to 24 (as humans like to) or counting from 0 to 23 (as computers like to). They amount to the same thing.