Resetting parts of a program
This recipe introduces, more formally, what we did at the end of the previous recipe when we began the process of resetting aspects of our story. Sometimes when we have a program running various settings, placement of objects, variables, and so on, are going to get changed. When we run the program next time, we'll want all of those things to start from where we originally had them.
Getting ready
The example that we'll go through here is resetting the placement of Frog on the stage. This way, each time you click on the green flag, Frog will return to the same starting position.
How to do it...
To get this started, follow these steps:
- Drag Frog (on the stage) to the place where you would like him to start each time the program runs. Examine the script -area settings and note the x: and y: positions that are given. From the following screenshot, we can see that Frog has an x -value of 18 and a y -value of -145:
- We'll need to know these numbers in just a moment. To reset the position of Frog each time, drag over a new green -flag block.
- Connect to this the go to x: y: block in the Motion category. Most likely, the numbers filled in match the location where your Frog is now. If not, just change the numbers to match what our screenshot has here.
Note
This new block is a different way to get movement. Remember when we said the stage can be thought of as a coordinate plane from math class? This block tells the sprite to go to a particular location on the stage. You won't see this one take any "steps" as we've seen with other movements. Actually, since your computer is pretty fast, you might not notice anything but the location of the sprite change!
How it works...
Programmatically, this recipe doesn't change a whole lot in the program. The main purpose is to ensure that everything starts uniformly no matter who is watching and controlling our program. This is a technique we'll use quite often throughout the rest of this book. It is also a common practice in other programming languages to declare variables (or as in this case, more like just resetting things).
There's more...
What if you wanted the movement to be noticeable? Not a problem! You can see that just a couple of blocks below the go to block is a glide block. Inputs to this glide block include the number of seconds in addition to the x-y coordinates, similar to the go to block.
If we were to replace our resetting block with this new block, we would see Frog glide to his position instead of just appearing there. The time it would take to "glide" depends on the number you input into this block.
See also
- To see more about the resetting aspects of the program, refer to the previous recipe, Basic broadcasting and receiving
- The next recipe, Other fun graphic effects, takes a look at other cool graphical effects we can incorporate into telling a story