Scratch is a fun-to-use program that teaches you about animating, programming, and building games. You already know this because you have been making simple games with Scratch for a while, and now you want to learn more. This project will use some of the most important Scratch tools and explain some basic game programming principles.
We will make an artillery game. You might know this type of game from the very popular Angry Birds series, but this is actually a very old concept, dating back to the earliest computers. It was an obvious choice for imaginative programmers to turn military calculations into a game, because computers were originally used to calculate missile trajectories.
We won't be able to guide any real missiles (luckily) with the scripts in this game. Instead of using proper mathematical calculations, we will use some simple tricks to get the desired results.
In games, it is rarely necessary to be absolutely realistic. Sometimes, bending the rules of reality creates more spectacular results; take Angry Birds, for instance:
We won't build a game as sophisticated as Angry Birds straight away. Our example will be more bare bones but still fun to play. In later projects, we will look back at this first example, and you will be challenged to add new things to this game to make it more interesting.
In this project we will be:
Creating a new project
Creating a parabolic shot
Creating a landscape
While doing this, you will learn about (among other things):
Drawing with Scratch
The xy-coordinate system
Operators and conditions (what has to happen and when)
The very useful cloning feature to quickly duplicate objects
To get started, go to the Scratch website (scratch.mit.edu) and start a new project by clicking on the Create button at the top of the page. If you already have a Scratch account, it might be useful to log in first, so that you can save your work in your account. If you are new to Scratch and are unfamiliar with the interface, have a look at Appendix, The New Scratch Interface.
We need to make sure that we're logged in and ready to get to work on a new project. We'll then draw some sprites and assemble our awesome cannon (and cannonballs). The Scratch menu bar gives us the option to explore the existing projects from other users (using Explore) or create a new project ourselves (using Create):
You are presented with a new project, including the Scratch cat as usual. We won't use the cat, so you can right-click on the sprite, and choose delete. A sprite is the official name for a 2D computer image. Most Scratch projects are built using sprites. You can find an overview of all the sprites used in a project in the bottom-left corner of the screen, underneath the stage.
The cannonball will be the main actor in this game because it will be the object that "blows things up". There are a few ways to add a new sprite to the stage. We can draw a sprite, select a sprite from the Scratch library, or import it from our hard drive. It's also possible to take a picture with a webcam.
To draw sprites, we perform the following steps:
Select the Ellipse tool (the circle) seen on the right-hand side of the drawing canvas. Click and hold the left mouse button and drag it. You will probably end up with something that's not quite a circle.
Undo your drawing with the back arrow button at the top of the drawing canvas. When things go wrong, you can always go a few steps back. You can even clear the entire screen (using Clear) and start over.
To create a perfect circle, hold Shift while dragging the mouse. Don't make your circle too big. It has to be able to move about the stage freely without bumping into the edges all the time.
Your cannonball is now done and ready for business. It will look like a simple grey dot as in this screenshot:
Let's move on to creating a cannon to shoot from. The cannon will consist of two parts: the back of the cannon, which serves as the pivot point, and the barrel. The following are the steps to create them:
Start again by creating a circle. This circle should be slightly larger than your cannonball.
Next, select the Rectangle tool that is right above the Ellipse tool.
Draw a rectangle that is as high as the circle but about three times as wide.
Click on the Select tool and drag the rectangle to overlap the right half of the circle.
Make sure that the center point of the cannon is placed at the center of the circular element, near the back of the cannon.
We name this sprite
Let's have some fun making the cannon shoot its cannonball. It's always a good idea to script and test the interactive parts of your game as early as possible. Without scripts, it's just a bunch of pretty pictures! They might be nice to look at, but they won't keep the player entertained for long.
In this case the objects are visible. Our sprites are our objects. We have a cannonball and a cannon. The player will be able to control the direction of the cannon. The cannonball will fly away in a certain direction based on which way the cannon is pointing. So the way things are controlled is:
player â cannon â cannonball
Click on the Data category. This is where you can create variables.
We will now click on the Make a Variable button.
Name the variable
directionand make it available for all sprites.
We start the program with the when <green flag> clicked block. This is the easiest way to set any program in motion.
Underneath it, we will place a forever block, because we will check the cannon's direction indefinitely.
If you want, you can tick the checkbox to make the variable visible on stage. Then, you can see the direction that the cannon is facing in, at all times.
Put a set () to () block in the forever block and select direction.
View the Motion category and look down at the list of blocks to find the built-in cannon direction variable. Place it in the open space. It may look superfluous to send the built-in variable value to a self-made variable. We do this because Scratch can't send built-in sprite variables to other sprites directly. Our self-made variable can be used in all sprites.
This is all the scripting that has to be done for the cannon. The following is the finished script:
Variables are an important part of programming. They allow you to store information for later use and to transfer information between different objects. A variable consists of two things; a name by which it is recognized and the word/number/object that it stores.
The easiest way to think about it is to compare the variable to a jar of pickles in a grocery store. The store clerk is the computer. He handles this jar and all the other jars that are available in the store. The jar is a variable.
On the face of it they all look the same, like glass containers. It's hard to distinguish one jar from another. That's why every jar has a label with a word on it. This is the name of the jar/variable. Most probably, the name of the jar will say something about what's in the jar. The jar of pickles, for example, will be called "Pickles".
You move up to the counter and ask the clerk, "How many pickles are in the Pickles jar?" and the clerk checks the jar, counts the pickles, and says, "There are 9 pickles in the jar." You now know something about the content of the Pickles jar. You feel like having a snack and decide to buy two pickles. After you paid and received the pickles, you ask again, "How many pickles are in the Pickles jar?" and the clerk counts the contents of the jar again (just to make sure) and answers, "There are 7 pickles in the jar."
It's most common to store numbers in a variable, because computers like to work with numbers, but variables can also contain names or even whole objects. Scratch keeps it simple, though. Scratch variables can only contain numbers or names/words.
Perhaps, it's better to illustrate the explanation of variables with the following screenshot:
The cannonball will also be triggered with a when <green flag> clicked block. Its actions will also be contained inside a forever loop.
Place a move () steps block inside the forever block. That's the basic necessity to set the sprite in motion.
Place a go to () block on top of the move () steps command and select cannon. This makes the cannonball hop back to its starting position.
Make the cannonball copy the cannon direction with a point in direction () block and by insetting the direction variable. Note that this is our added variable (orange background) from the Data category, not the built-in (blue background) variable from the Motion category. The variable with the orange background is the saved cannon position. In this case, the variable with the blue background is the current direction of the cannonball, which wouldn't change anything when applied to itself.
Put a repeat until () block around the move command.
Then, place a touching () condition block in the vacant space and select edge.
Now the cannonball will angle itself in the same direction as the cannon, and it will keep moving forward until it reaches the edge of the stage. At that point, the script repeats and the cannonball is reset to its starting position in the cannon. The following is the completed script:
We're not building any fancy controls at this point. Click on the i button in the top-left corner of the sprite in the Sprites window:
This will switch the sprites view to the sprite properties screen. Here you can view and edit some information about your sprites. An important one is the sprite name; you can name the sprite here if you didn't already do so in the sprite editor during its creation. Notice the sprite name in the top field of the properties screen:
Click on and drag the little blue pin to change the direction that the cannon is facing in. Try it and see how the cannonball shoots in different directions depending on the direction of the cannon.
Don't forget to click on the green flag at the top of the stage (if you haven't already) to activate both scripts!
This game will be no fun without something to shoot at and blow up. So, we are going to create some targets for the cannonball to hit. We will first draw a new sprite. Then, we are going to use a very cool new feature of Scratch 2.0: the ability to create copies of a base object. This can save a lot of time when you want to have multiple objects that work the same way. This is often the case in games. Think of all the enemies you've squashed or all the coins you've picked up in various action games.
To create the target, follow these steps:
Create another new sprite with the Paintbrush button.
Select the Ellipse tool and make sure the fill color is red and the border color is white.
Adjust the line thickness to create a fairly thick line.
Draw a vertical oval shape.
Don't worry too much about the size. We will adjust the proportions later. It's easier to draw big shapes first, so you can easily see the details and relative placement. When the drawing is complete, you can scale it down to the desired size. First, we need to create two more oval shapes.
Click on the Ellipse tool.
Place your cursor over the existing oval at the top-left edge of the red fill.
Click on it and drag to the lower-right edge of the red fill to draw another oval. This oval will fit neatly inside the first one.
Repeat these steps to create a third, even smaller oval.
Click on the Duplicate button in the toolbar.
Click on the oval shape you have already made.
When you move the cursor, you will see a transparent "ghost" of the circle, moving along with the cursor.
Click anywhere on the drawing canvas to place a copy of the oval there.
Use the scaling widgets you see around the shape when it's selected, to scale the copied circles down to the right size.
Drag them inside each other to create the finished target disk.
Click on the appropriate sample from the color swatches to change the line color to brown.
Click on the Line tool and draw a vertical line, about as high as the target disk.
Draw another line diagonally down from the upper tip of the first line.
The two legs of the target stand are complete.
Click on the Select tool and drag a box around the entire target disk. This will select all three shapes as a single object.
Perhaps, your shapes are overlapping in the wrong way, with the stand on top of the disk, instead of underneath it. This means that the shapes are sorted in the wrong order. A Scratch drawing consists of separate layers, like sheets of transparent papers stacked on top of each other. The sheets on the top will cover the sheets underneath. This way you can create the illusion of depth, by placing objects that should be far away at the bottom of the stack.
Change the order of shapes with the Forward a layer and Back a layer buttons, if needed.
We will write a script for the target we just drew; this script will place copies of the object at random locations on the stage. To do this we will use the new clone block. This is one of the most exciting new features of Scratch 2.0. Instead of manually copying your sprites N number of times, you can just use a script to do this work for you. It can save a lot of time when creating and editing objects.
This script will start with a when <green flag> clicked block, just like the earlier ones.
Attach a go to x: () y: () block. Fill in the numbers
About X-Y coordinates
X stands for the horizontal position, that is, how far left or right something is. Y stands for the vertical position, that is, how high or low something is. This way the computer can easily save the position of any object on the stage. Look at the bottom-right corner of the stage. Here you will see the current position of the mouse shown as X and Y coordinates. This can be a helpful tool when deciding where you want objects to appear on stage with a script. Just point to the right place, look at the numbers, and put them at the right places in the script.
The center point of the Scratch stage has the coordinates (X:0,Y:0). The horizontal positions range from -240 to +240. And the vertical positions range from -180 to +180. If you look at the assignment for the previous target, you will notice that the target is placed somewhat left of the center (-100) and on the center line vertically (0).
Next, add a show block. Yes, the sprite is already visible now, but at the end of the script we will make it disappear. This block makes sure it appears again in time when the script runs.
Attach a repeat () block and fill in
Inside the repeat () block place a move () steps block.
Instead of a fixed number, use a pick random
80block to make the spots where a target will appear a little unpredictable and more interesting.
Then, attach the new create clone of () block underneath the move command inside the repeat block. Select myself.
Finally, use the hide option on the original sprite. Place this block at the end, outside the loop.
So now we have a cannon, a cannonball, a bunch of randomly created targets, but still no exciting game. The cannonball can fly through the air, but it doesn't do anything when hitting a target; it just passes right through. This can be easily fixed.
Start a new script in the target object with a when I start as a clone block.
Attach a wait until () block. This will pause the script until something happens.
Place a touching ()? condition block inside the slot. Select cannonball.
The next step is to attach a wait () secs block.
Fill in a very short time of
0.05seconds. This might seem a little useless, but it will give the other scripts (specifically the cannonball script in this case) time to respond before the target disappears.
The last step is to delete this clone.
The targets disappear when hit by the cannonball, but the cannonball can go on through multiple targets. This makes the game a bit too easy. It would be better if the cannonball is stopped by hitting a target as well. So a new cannonball has to be aimed and shot for each target.
Making the cannonball disappear on contact with a target just requires a little addition to the existing script. The cannonball is already reset to its original position when hitting the stage edge. We can use this already existing script and also check for hitting a target.
Click on the cannonball sprite in the Sprites view to see its scripting panel.
Grab an () or () operator block.
Pull the touching <edge>? block from the script and place it in one of the () or () slots. It doesn't matter which one.
Also get a new touching ()? block. Place it in the other slot and have this condition checking for
target. (Have you already properly named your target sprite?)
Place this entire conditional structure in the now vacant condition slot in the existing script.
Currently the cannonball is moving on in a straight line. In reality, a cannonball doesn't move like that (but we'll be fixing this). It is heavy, and what goes up must come down. You can try it yourself with a ball or a stone. Throw it upwards in front of you and see what happens. Just be careful with the neighbor's windows!
The ball will move upwards in the direction you threw it. At some point it will start to slow down, stop, and then start falling down. The path the ball follows is called a parabola. This is what we expect of gravity. It's always around us, so we don't pay too much attention to it. If you would throw the ball in space, which has no gravity, the ball would move on forever in a straight line, as it does now in our game. On Earth, the ball will move up for a while, then slow down, and eventually fall down again. This movement path is described in the following diagram:
In this case, the cannon and cannonball should be on the ground, so we want to simulate some gravity. Not only will the parabola trajectory look more interesting, it will also make the game more challenging. You could try hitting a target by shooting the cannonball at a steep angle and have it hit a target as it drops down. It is very useful to shoot over the hills, which we will do in the last stage of this project.
To simulate gravity, you could use a realistic mathematical formula. But it can be hard to figure out, and in a simple game, it often isn't needed. We are going to create a good-looking parabola trajectory with just a simple calculation and some trickery.
To simulate the pull of gravity, we are going to use the built-in timer variable. This timer will start counting seconds when the game is started, but we can reset it to start counting again. We will be using the increasing number as a constantly increasing pull, which will eventually start dragging the cannonball downwards.
We select the cannonball sprite to add to its scripts.
After the move () steps command, add a change y by () block. This will cause the cannonball to vertically move a bit after taking its steps.
Place a () * () (multiplication) operator in the box.
Then put the timer variable in one of the operator slots.
In the other slot, fill in a number manually. Try a few numbers, just for the fun of it, and see what happens.
In my opinion, the number -5 has the best result. But if you disagree, you're free to choose another number. Just make sure that the number is negative, because a positive number will cause the cannonball to float ever faster upwards.
To reset the timer after the cannonball has hit something, add a reset timer block at the start of the loop.
As the final stage of this project we will create a hill for the targets to sit on. The landscape will have a diagonal slope; we have to change the parabola trajectory to shoot at different points on the hill. The finished game will look like the following screenshot:
First, create a copy of the cannonball by right-clicking on the sprite in the Sprites view and choosing duplicate, shown as follows:
Click on the i button on the copied sprite and change its name to
Throw away the scripts in the copied sprite. Those are only useful for the cannonball, not for the drawing tool.
Switch to the Costumes tab and change the color of the drawing tool to dark green using the color swatches. This is mostly to make it visually different from the cannonball, so that we don't confuse the two.
Go back to the Script tab so that we can create a new script for the drawing tool.
We start the script again with a when <green flag> clicked block.
Attach a pen up block to make sure the tool doesn't draw anything while moving to its starting point.
Add a clear block. This might not look useful now, but like with the hide and show commands in the target sprite script, this will help clear the screen once we want to restart the game.
Move the tool to its starting point with a go to x: () y: () block.
240after x and
0after y, so the tool starts at the right edge of the stage.
Choose a green color for a natural-looking hill in the set pen color to â¦ block.
Place the drawing tool on the stage with a pen down block. We are now ready to start drawing the landscape.
Then, we move the pen diagonally to the bottom edge with a go to x:
-180block. Because the pen is down, it will draw a line between its start and end point.
To make full use of our newly drawn landscape, we have to set the targets down on them. But how do we do that on such an uneven surface? The solution is to slowly move the targets down and use another collision test to decide when the targets have reached the landscape and should stop moving. We add the following script to the target sprite:
Click on the target sprite so you can view its scripts.
Add a repeat until () block at the start of the clone script.
Inside the repeat until loop place a change y by () block and fill in a negative number to make the targets move down.
I filled in the number
-4for a fairly slow speed. You may take bigger steps, but then the targets could end up being stuck partly through the landscape. Not a big issue, but it might not look as nice.
To stop the targets from moving when they reach the landscape, add a touching color ()? condition to the repeat until () block.
Click on the color box and then point and click on the green line that you've drawn.
Computers are very precise about color. Keep this in mind if your color collision doesn't work. Most likely, the actual color of the object will be slightly different from the color that you checked for. You can't see it with the naked eye, but the computer can tell the difference based on the color number. The finished script should look like the following screenshot:
Now that we have another object on the stage, that is, the landscape, there is one more thing we have to do to finish the game. When the cannonball hits the ground, it should stop instead of moving straight through the landscape. This is similar to the addition we added after including the targets. Now we only need to add another collision check for the cannonball to respond to.
Get another () or () operator block.
We will check for hitting the green landscape color, just like we just did with the targets.
In the other slot, we will place the entire condition check, like we made earlier. So our latest () or () block will become the outermost block in the construction.
Place the entire construction back in the repeat until () slot and we're done.
Your first game is now done, well, sort of. You learned how to draw sprites and how to add scripts to them to make them interactive. We used the new cloning feature to quickly copy the same sprite, including its functionality. We worked with collisions between objects, some variables, and simulated gravity to create a simple, but challenging game. The finished game will look like the screenshot that follows:
It's still far from the Angry Birds example that we mentioned at the start, but all the basic elements are there. Test your game, and play with the numbers a bit to see how they can affect the playability! Have a go with the following tasks:
If you increase the cannonball speed to very high, it will become very fast, but hard to control.
Try increasing or reducing the number for the simulated gravity effect.
Do you still know which number that is? It is somewhere in the cannonball script.
Can you change the number so it feels like the game takes place on the moon, where gravity is not as strong as it is on Earth?
In later projects, we will look back at this game and you will be challenged to expand and improve it, based on the things you will learn in those projects. The game might not look like anything special just yet, but with some effort and imagination, you could make it into an exciting game to rival Angry Birds.