In this video, you'll program
the background sprites to scroll.
In the starter project, three different cave sprites
act as the background.
The first cave sprite is red, the second is blue,
and the third is green.
In this example, one cave sprite
closely follows the next forming what
looks like a continuous scrolling background.
In the starter project, there is code
that's been added to each cave sprite.
This code starts the first cave at x times 480,
the second at two times 480,
and the third at three times 480.
The code also contains a variable, distance traveled.
Each time these loops run, each sprite
goes to a new position based on the value
of distance traveled.
You can imagine how this might look outside
of the Scratch Viewer.
Imagine you have three sprites
that are all 480 pixels wide.
You need to set the first to start
with an x value of 480, the second to start
with an x value of two times 480, or 960,
and the third to start at an x value
of three times 480, or 1140.
The distance traveled variable increases
as the sprite moves, advancing the background sprites.
When distance traveled equals zero,
the sprites stay at the current position.
When distance traveled equals one,
the sprites all move to the left one step.
When distance traveled equals two,
the sprites all move to the left another step
and so on until the backdrop has scrolled
all the way across the stage.
To make the backdrop scroll,
program the distance traveled variable
to increase throughout the game.
Click the player sprite and drag out
a change distance traveled block.
Add a when flag clicked box above this.
Click the flag a few times to test this code.
Each time the program runs, the value
of distance traveled goes up by one
and the caves move one step to the left.
If you try a higher value, like 50,
you can scroll through all the caves
just by running the code a few times.
Next, increase the value of distance traveled repeatedly.
Add a forever loop from the control menu
to the change block.
Click the flag to test.
Whoa, that was fast.
If you click the flag to test again,
the program won't run.
The distance traveled variable holds a value.
When you start the game, the variable
is still holding the value of the distance traveled
from the last game.
To fix this bug, add a
set distance traveled to zero block under
the when flag clicked block to reset the game.
Click the flag to test.
Great, the distance traveled variable
starts at zero, then increases.
Tinker with the value
in the change distance traveled block
until the sprites scroll across the screen
at a pace you like.
Now it's your turn.
Add a change distance traveled by block
and a green flag event, a forever loop,
and a set distance traveled to block.
Program the distance traveled variable
to increase throughout the game.
Set the distance traveled to zero
when the flag is clicked.
In the next video, you'll control
the rising and falling of the player sprite
with an if-else statement.