In this screencast, you will learn how scrolling backdrops work, then, you’ll program yourown background sprites to scroll. Watch this screencast first to learn what to do, thenyou’ll get the chance to try programming it on your own.
In this starter project, three different cave sprites act as the background. The first cavesprite is red, the second is blue, and the third is green.
In this example, you can see that one cave sprite closely follows the next, forming whatlooks like a continuous, scrolling background. In the starter project, you’ll notice thatthere is already code created for each cave sprite.
This code starts the first cave at x = 480, the second at 2 times 480, and the third at3 times 480.
This code also contains a variable: distance traveled. Each time these loops run, eachsprite 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 threesprites that are all 480 pixels wide. You need to set the first to start with an x valueof 480, the second to start with an x value of 2 times 480 (or 960), and the third tostart at an x value of 3 times 480 (or 1,140). To move these sprites, you’ll need to usea variable called “distance traveled,” which will go up continually as the sprite moves.
To get your backdrops to scroll, you’ll need to program the distance traveled variableto increase throughout the game. To start, click the player sprite and dragout a “change distance traveled block” from the data menu. The cave sprites startrunning their code when the flag is clicked, so to test how this block works with the cavesprites, add a flag event here as well.
Click the flag a few times to test this code.
You should see that each time the program runs, the value of “distance traveled”goes up by 1 and the caves move 1 step to the left.
If you try a higher value, like 50, you can scroll through all of the caves just by runningthe code a few times.
Great, now you need to program the computerto increase the value of distance traveled repeatedly.
Add a forever loop to your block stack and try that.
Whoa, that scrolled really fast! This program can only be run one time.
If you try it again, nothing happens. This is a common type of bug that computerscientists encounter. The distance traveled variable holds a value. When you start thegame, the variable is still holding the value of distance traveled from the last game. Tofix this, add a “set distance traveled to 0” block that will run right after the flagis clicked. Try that.
Nice work! Now distance traveled starts at 0, and the computer is constantly increasingits value. What do you think about the speed at which the background is changing? Too slow?
Too fast? Tinker with the value in the “change distance traveled by” block until the spritesscroll across the screen at a pace you like.
In the next screencast, you’ll control the rising and falling of the player sprite withan if-else statement.