Merry Christmas fellow Scratchers! Here is a little game-cum-greeting, remixed from MyRedNeptune's original project, Christmas Night, that I am quite fond of.
To the seasoned Scratcher, remixing is not a new concept. If you are just beginning to scratch, you might be wondering what it is all about. A remix is what results when you download another Scratcher's project and create something new or different with it. On every project page at MIT Scratch website, there is a link you can click to see a map of remixes. The remix visualization for the original Christmas Night is quite dense as it has undergone changes by many a-remixers, me included.
The opportunity to remix is as significant to learning as the fun and creativity it entails. The good MIT folks created Scratch as a form of teaching and learning, and the ability to download and read someone else's code and thought process helps accelerate the learner's understanding and programming skills.
To me, any invention is created twice, first in a person's mind, and second in the physical world. Scratch gives me first the enjoyment of seeing others' inventions, then the wonderment of appreciating their logical thinking that led to the creation - all thanks to this sharing philosophy.
Fortunately, many software in the world are created with the same philosophy in mind. Image processing software like Gimp or Blender (that some Scratchers may use to make sprite costumes), text editors like Emacs, Vim, Notepad++, and many, many more are open source. Open source means that the code that creates the software is free for download, so you may understand how they work, or even enhance them if you like.
The word free here does not refer to monetary aspects (unlike "free candies"). Although most open source software do not cost a dime, there are those which do.
No, it is free as in "freedom", as in having the "liberty" to learn and create. That, folks, is the spirit of great learning and sharing. Merry Christmas.
Saturday, December 24, 2011
Wednesday, December 21, 2011
Christmas Night
Three days to Christmas we are! I found this Christmas Night Scratch game by MyRedNeptune game that I want to share with all:
It's been liked and downloaded a lot, so others must have enjoyed it as much as I have. What first struck me about the game is how simple it was. Then I realized that the pulling factor for me is the scoring display with its cute line up of little presents. The other drawing factor is the idea of Santa upgrading himself to a plane - powered by environmentally friendly magic fairy dust, I am sure =)
So, I took a look at the script to see how the scoring display works. The idea is simple. It uses two sprites: one of them, No Presents, has 50% ghosting effect that always stays on stage, giving clue to the number of presents that needs to be delivered to get to the next stage.
The other sprite has lots of costumes with increasing number of presents. It stays in front of the No Presents sprite previously mentioned, and switches to the next costume as a present successfully reaches a chimney. The last costume is a line of ten presents but all in white. It alternates between the one with colours to give a flashing effect.
Now, isn't this neat?? Gotta love the simplicity. I remixed this project into a game-cum-greeting. Will post it up tomorrow.
It's been liked and downloaded a lot, so others must have enjoyed it as much as I have. What first struck me about the game is how simple it was. Then I realized that the pulling factor for me is the scoring display with its cute line up of little presents. The other drawing factor is the idea of Santa upgrading himself to a plane - powered by environmentally friendly magic fairy dust, I am sure =)
Adorable score display |
Two sprites for the score display |
Three out of eleven of Score sprite's costumes |
costume10 and costume11 alternate to give flashing effect on the display |
Project: Fruit Basket Mini Game
Recently, I posted a Scratch tutorial on summing or updating scores with sound effects, like in a game show. In today's project I will show how that is applied in a mini time-based game. In this game, players have one minute to catch as many fruits as they can. Each fruit earns the player points:
After one minute, the game ends and the final score is decided based on the number and types of fruits caught. Play to experience it for yourself (the sound quality is horrendous in this online version - you may download and run on your computer for the music notes to play better):
We will program this game in four steps.
All the orange blocks in this script do two things: first, they hide all the variables so that the watchers are hidden. We also set all the variables to zero.
We have six variables in this game. We use those named after the fruits to keep track of the number of fruits collected. We will see how to do this in Step 3. In Step 4, we will use the values in these variables to arrive at the final score, which we put in the totalScore variable.
When the basket receives the broadcasted message to start the game, it shows itself and for the next 60 seconds, keeps checking whether the left or right arrow keys are pressed. If the right arrow key is pressed it moves 8 steps to the right, and if it is the left arrow key it moves the same distance to the left.
Once the 60 seconds is up, it broadcasts "end" to signal that the game has ended. We will make use of this "end" message in Step 4.
The Cherry is the first fruit to appear, and it starts falling right immediately when it receives the 'start' signal:
The Cherry first sets its instrument to #13, which is the Marimba. Next, it shows the variable that counts the number of cherries the player collects (with the show variable cherry block), and appears on stage (with the show block).
Then, for the next 60 seconds, it repeatedly:
The script for Lemon is almost the same as Cherry's. Lemon appears only after 10 seconds into the game, so we insert a wait until (timer > 10) block to ensure this:
All the fruits - Pear, Plum and Pineapple - have the same script as the lemon. They are different in terms of:
The Score sprite detects that the minute is up and that the game has ended once it receives the broadcasted "end" message. To this, it shows its first costume, which says "Time's Up!". It waits two seconds, to be sure that the player reads that, and switches to the next costume, which says "Your total score is:"
It then proceeds to do a game show flavour of totaling up the scores using the Scratch script template from the game show scoring tutorial. Note that in this game, we increase totalScore by 1, 2, 5, 10 or 20 for each count of cherry, lemon, pear, plum and pineapple respectively.
Cherry | : 1 point |
Lemon | : 2 points |
Pear | : 5 points |
Plum | : 10 points |
Pineapple | : 20 points |
After one minute, the game ends and the final score is decided based on the number and types of fruits caught. Play to experience it for yourself (the sound quality is horrendous in this online version - you may download and run on your computer for the music notes to play better):
We will program this game in four steps.
Step 1: Do staging and initialization
We have two backgrounds for the stage - one with the game title "Fruit Basket" and another without. This script basically displays the one with the title at the beginning of the program, and only switches to the next background when the player hits the spacebar. Since this game is timed, we also reset the timer before broadcasting a message to start the game.Script to change stage background and initialize variables |
We have six variables in this game. We use those named after the fruits to keep track of the number of fruits collected. We will see how to do this in Step 3. In Step 4, we will use the values in these variables to arrive at the final score, which we put in the totalScore variable.
Step 2: Control the basket
Script to control basket |
Once the 60 seconds is up, it broadcasts "end" to signal that the game has ended. We will make use of this "end" message in Step 4.
Step 3: Program the falling fruits
We want the fruits to fall in differing speeds and stages. The more points a fruit is worth, the later it will appear in the game, and the faster it will fall. When the player successfully collects a fruit we will also play a note. The instrument that we use for each fruit will also be different.The Cherry is the first fruit to appear, and it starts falling right immediately when it receives the 'start' signal:
Script for Cherry |
Then, for the next 60 seconds, it repeatedly:
- Positions itself somewhere at the top of the stage, with the set x to_ and set y to_ blocks.
- Keep falling until either it touches the basket (I use touching color block here, but you could also use the touching sprite block), or if it has reached the bottom of the stage (when y position is less than -170), or if time is up.
- Checks if it touches the basket. If it has, then it adds to the count of cherries collected with the change cherry by 1 block. It also plays the 65th note of the Marimba for 0.01 beats.
The script for Lemon is almost the same as Cherry's. Lemon appears only after 10 seconds into the game, so we insert a wait until (timer > 10) block to ensure this:
Script for Lemon has the wait until (timer > 10) block |
- instrument used (observed in the set instrument to_ block)
- time to appear (observed in the wait until_ block)
- falling speed (observed in the change y by_ block)
- the variable to update (observed in the change_by_ block)
Step 4: Display final score
Remember the "end" message that we broadcasted in Step 2? This is where we use it.Scoring script adapted from the game show scoring template |
It then proceeds to do a game show flavour of totaling up the scores using the Scratch script template from the game show scoring tutorial. Note that in this game, we increase totalScore by 1, 2, 5, 10 or 20 for each count of cherry, lemon, pear, plum and pineapple respectively.
Game show scoring
I have put this Scratch tutorial in a project itself, so you can simply watch it. Feel free to download the script template for score keeping (or as I call it, gameshow scoring) and reuse in your own projects!
If you prefer reading the tutorial, then continue on…
Tutorial: Game show scores on Scratch
We do this in only two steps:1. Prepare variables
Obviously, we need at least one variable for the scores, and an additional one to keep the total. In this tutorial, we will create three variables for the scores (i.e. score1, score2, score3) and another (i.e. totalScore) for the total score. In my tutorial project above, I populate score1, score2 and score3 with random numbers for illustration purposes. Normally, we would use them to keep more meaning scores. You may look at the the Fruit Basket project to see how I use them to keep count on different fruits.2. Do the scoring
The main idea here is that we want to sum up score1, score2 and score3, and put the sum in totalScore. We could have just gone and set totalScore with the sums like this:Summing up scores (in a boring way) |
Summing up score1 (in a more interesting way) |
Wait 0.5 seconds before appending similar blocks to sum up score2 |
Appending similar blocks below to sum up score3 |
Monday, December 19, 2011
Project: Malibu Beach Crab
What comes to your mind when you think of the beach? Sand castles, surfers, ice cream under the shades and maybe even a nice swim in cool clear seawater.
I think of crabs. Not the hordes of hermit crabs that flood some beaches, but tiny little crustaceans no bigger than the fingertip with soft translucent shells. They emerge from holes in sand washed and wet from the waves.
With Scratch, we need not be confined to reality. Let's take our imagination further. This is what we will create:
There seems to be a lot going on in this project but we'll soon see that the idea is really simple. Basically, the entire project breaks into four steps.
I think of crabs. Not the hordes of hermit crabs that flood some beaches, but tiny little crustaceans no bigger than the fingertip with soft translucent shells. They emerge from holes in sand washed and wet from the waves.
With Scratch, we need not be confined to reality. Let's take our imagination further. This is what we will create:
There seems to be a lot going on in this project but we'll soon see that the idea is really simple. Basically, the entire project breaks into four steps.
Step 1: Setting the stage
There are two stage backgrounds. The first background has a short introductory text to the game. What we want to display this from the beginning of the program until the user hits the 's' key to start the game. This is how the script looks like:
Script for the stage |
It displays the first background, and switches to the second one on 's' key press. At this point, we also reset the points variable that we'll be using to keep score. Then we broadcast a "start" message. We will see in the following steps that we program all sprites to respond to the "start" message.
Step 2: Controlling the crab
In the Run, Scratch, Run! project, we have seen how to program movement controls on a sprite with the keyboard. We do the very same thing here:
Script to control the crab |
The difference in this script is that we use the glide blocks to simulate jumping. Notice that we constrain the crab to the same x position when it glides. So the crab only moves vertically upwards to the y-coordinate of 100, and then back to -111. (You may find it interesting to compare this to the jumping script in the Run, Scratch, Run! project. The Three Ways to Program Falling Objects in Scratch tutorial briefly mentions the difference between using glide blocks and changing position coordinates in a loop.)
Step 3: Moving the bananas, suns and fruit platter
If you play the completed program above, you will see that the bananas and suns appear to fall rather haphazardly from the sky. Let's take a look at the scripts that we use to make the banana and sun sprites fall:
Script for a banana sprite |
Script for a sun sprite |
They are actually the same! The minute difference lies in the wait_secs block, where we pick a larger random number for the sun. So what's going on here? When the sprites receive the "start" message, they hide themselves - this clears the stage when we replay the program. Then, they repeatedly do the following sequence:
- Reset their own positions to somewhere at the top of the stage. We purposefully set the y-position 240, which is safely offstage since the stage covers up to 180 in the y-axis. We want them to fall anywhere from the top of the stage. This means that we will need to vary the starting x-coordinates. we do this by selecting a random number that is within the range of the stage.
- Wait for a random number of seconds. We do this because we want the sprites to fall unpredictably. If we had specified a constant number, the player will be able to time the falls - that's no fun when playing a game!
- Show themselves and fall by gliding to the bottom of the stage.
Why do me make the sun sprites wait longer than the banana sprites? We do this because we want the bananas to fall more frequently than the suns. The game will be more challenging if the suns fall very often. See this for yourself - download the project and experiment with the script.
Next, we move the fruit platter. This is the most satisfying "food" for our crab. It does not fall from the sky, but moves horizontally across the stage. The crab will need to just to "eat" it. This is how we make the fruit platter move:
Script for the fruit platter |
This script is also about the same as those for the banana and sun! It repeatedly does the same three main things: reset position, wait, and glide. This time however, the fruit platter resets its position to a fixed location at the top left of the stage. Also unlike the banana and sun, when the fruit platter glides it keeps the same height on stage while changing its x position to move from left to right.
Step 4: Keeping score
Here is a more exciting part of the program. We have created a variable, called points, to keep score. We want to change the value of points depending on what the crab has eaten. One eaten banana is a point, while a fruit platter gives 20 points. Getting touched by a falling sun however, loses 10 points. To do this, we will need to keep track of whether a banana, sun or fruit platter has come in contact with the crab. To each of these sprites, we insert these scripts respectively:
Script to detect whether a banana has touched the crab |
Script to detect whether the fruit platter has touched the crab |
Script to detect whether a sun has touched the crab |
All we are doing here is to broadcast a particular message depending on what has touched the crab. If it is a banana the message is "eaten!", if it is a fruit platter then "eatenFruits!", and a sun, "sunBurnt!". On touching the crab, we make the sprites disappear using the hide block.
What happens to the broadcasted messages "eaten!", "eatenFruits!" and "sunBurnt!"? They are received by the crab:
Script for crab behaviour |
The crab does three things on receiving each of these messages. It updates points, plays a sound and says something. For example, when a fruit platter touches the crab, it broadcasts the "eatenFruits!" message. The crab immediately receives this message, updates points by 20 more, burps, and says "BURRRRRRP!!!"
There we have it. A game in Scratch in just four simple steps.
Project trivia
I first created this project in May 2010 while assisting a five-day Scratch course for students from Nanyang Girls High School. It was held at the School of Computing, National University of Singapore and was great joy to do. Back then, I went by the username chapati on Scratch.
Tuesday, December 13, 2011
Project: Magic Wand
With Christmas so near, I sense magic in the air! Magic is exactly what we are going to program today - Okay, maybe that doesn't make it magical anymore…but anyways, this is what we will create:
I am not embedding the online version here because the wand does not behave as it should online. So, to see it in action you will need to download and run the project on your computer.
There are 16 sprites and 33 scripts in this project. Only five of them are unique - the rest are copies - and only four truly matter. Let's see what we have…
A "magical round thing" (yes, I have no better name for it. Ideas, anyone?) has four variables:
At the very start of the program the sprite stays "in the wand", so we set outOfWand to 0.
Then, when the sprite knows that the the mouse is clicked, it will proceed to set the other variables. However, it only does this when it is not out of the wand yet. We really don't want to mess with these variables if the sprite's already on stage. Note that it now sets outOfWand to 1, indicating that it is now ready to emerge. It then positions and shows itself at the wand tip with the go to Wand and show blocks.
The rest of the code in the repeat until (outOfWand = 0) block controls the behavior of the sprite after it has emerged:
First, it changes its colour effect. Then it falls down and to the right or left depending on the random values that u and dv were set to.
It also checks whether it is touching the edge of the stage. If it is, then it hides itself and sets outOfWand to 0 to indicate that it has left the stage and - in a sense - has gone back in the wand. This means two things:
I am not embedding the online version here because the wand does not behave as it should online. So, to see it in action you will need to download and run the project on your computer.
There are 16 sprites and 33 scripts in this project. Only five of them are unique - the rest are copies - and only four truly matter. Let's see what we have…
The wand
The wand is easy to code. Easy to create too. I drew it on the Scratch Paint Editor using two lines of different shades. Its script simply instructs it to follow the mouse pointer at all times:Scripting wand to follow the mouse pointer |
The stage
I put this script on the Stage, but it could really be on any sprite. All this script does is to broadcast a "click" message when it senses a mouse down event.Broadcast 'click' when mouse down event occurs |
The magical round things
These are the stuff that emerge out of the wand tip. They each have a copy of the same script and their own variables.A "magical round thing" (yes, I have no better name for it. Ideas, anyone?) has four variables:
- outOfWand indicates whether the sprite has shot out of the wand and is moving on the stage. When outOfWand is 0, it means that the sprite is not on stage - you can think of this as the sprite being "inside the wand" and has not emerged yet. When outOfWand is 1, it means that the sprite has left the wand and is out on stage.
- v is the y-coordinate change for the sprite.
- dv controls the rate of fall for the sprite. You would easily understand what v and dv do if you have seen past tutorials and projects related to falling. (If you have not, you may want to take a look at some of these: Programming Falling Objects in Scratch, Three Ways to Program Falling Objects, Keep Afloat, and Run, Scratch Cat, Run!)
- u is the x-coordinate change for the sprite. We want the sprite to fall some distance to the left or right of the wand. u is the change in x that will help do this.
Initialize outOfWand to zero when program starts |
Setting values of variables when 'click' message is received |
The rest of the code in the repeat until (outOfWand = 0) block controls the behavior of the sprite after it has emerged:
Behaviour having emerged from the wand |
It also checks whether it is touching the edge of the stage. If it is, then it hides itself and sets outOfWand to 0 to indicate that it has left the stage and - in a sense - has gone back in the wand. This means two things:
- The repeat until block terminates, since outOfWand is now 0.
- The next time the mouse is clicked, the if (outOfWand = 0) block will evaluate to true and it will continue the process of resetting its variables and emerge again.
Monday, December 12, 2011
Project: Happy Calculator
Here we are again with another Scratch project! We are going to program a simple calculator. Scratch has built in operators that we can use and we will use the ready-made addition, subtraction, multiplication and division operators.
We will also program the power function in our calculator by doing appropriate numbers of multiplication - we will see how to do this later.
Right now, check out the Happy Calculator program below!
I call the yellow fellow "Happy". Happy asks three questions: first to enter a number, then he asks for an operator, followed again by a number. He will then do the math on both numbers.
For example, we might do this:
Happy goes on to multiply 5 by 6, and shouts out the result, which is 30.
Here are the operators Happy knows about: +, -, *, / and ^
I am sure we are already familiar with the plus (+) and and minus (-) symbols.
At school, we write our multiplications with the x symbol e.g. 3 x 5 = 15
Here we will use * as the multiplication symbol. We will use / as the division symbol, and ^ as the power symbol. We will program Happy to understand these symbols.
More examples of math with our operator symbols:
Alright, now we are ready to program our calculator! I suggest downloading the project and have a look at the full script.
At the start, we set these variables to their initial values:
The script is pretty straightforward. We use the ask_and wait block and then we set a variable to the answer given by the user.
Notice that we use several broadcast blocks in our script. They are just there to signal the instructions sprite to appear and disappear. They are not the main focus of our calculation script, but you could always comment on this post if you need help with them.
We have a chunk of code here as you can see. They are actually just a lot of nested if-else blocks. I prefer this to snapping many if blocks together, since the whole "else" part is immediately ignored once the "if" condition is met. Basically, what we are doing here is to check the user's input for the operator symbol.
When the divisor is zero, we set the ans variable to "Anything divides zero is undefined!" This makes Happy a pretty smart talking calculator. If the divisor is anything but zero, we do division with Scratch's divide block.
So, what we do is to first set the ans variable to 1. The we multiply ans by num1, num2 number of times using the repeat block. For example, if num1 is 9 and num2 is 3, then we repeat 3 times the multiplication of ans to 9. At every loop of the repeat block we update ans to the latest multiplication result. Take a look at an example:
Suppose if num2 is zero, then the repeat block repeats for zero times, meaning that no further multiplication is done at all, and so ans remains at 1.
We will also program the power function in our calculator by doing appropriate numbers of multiplication - we will see how to do this later.
Right now, check out the Happy Calculator program below!
I call the yellow fellow "Happy". Happy asks three questions: first to enter a number, then he asks for an operator, followed again by a number. He will then do the math on both numbers.
For example, we might do this:
Happy: Enter first number We type 5 (and press Enter, or click the tick icon) Happy: Enter an operator We type * Happy: Enter second number We type 6 |
Happy goes on to multiply 5 by 6, and shouts out the result, which is 30.
Here are the operators Happy knows about: +, -, *, / and ^
I am sure we are already familiar with the plus (+) and and minus (-) symbols.
At school, we write our multiplications with the x symbol e.g. 3 x 5 = 15
Here we will use * as the multiplication symbol. We will use / as the division symbol, and ^ as the power symbol. We will program Happy to understand these symbols.
More examples of math with our operator symbols:
2 to the power of 3 | : 2 ^ 3 = 8 |
100 divided by 5 | : 100 / 5 = 20 |
13 multiplied by 6 | : 13 * 6 = 78 |
Alright, now we are ready to program our calculator! I suggest downloading the project and have a look at the full script.
Step 1: We need variables
We know that we are programming Happy to ask for input. When someone enters an input, we have to store it somewhere, or it just vanishes and our program will have no idea what the input was. To do this, we create variables. You could think of variables as boxes to keep things. We may store input in variables, or just any value we want. Here, we create five variables:- err that stores the sentence "Oops, I can't calculate this!" This is what Happy will say when something goes wrong.
- num1 that stores the first input number.
- num2 that stores the second input number.
- op that stores the input operator.
- ans that stores the final result of our calculation.
At the start, we set these variables to their initial values:
Setting variables to initial values |
Step 2: Happy asks for input
Having set those variables, we program Happy to ask for user input:Asking for and getting input |
Notice that we use several broadcast blocks in our script. They are just there to signal the instructions sprite to appear and disappear. They are not the main focus of our calculation script, but you could always comment on this post if you need help with them.
Step 3: We do math!
Script for calculation |
Addition, subtraction and multiplication
When the operator is +, - or *, we do the necessary math with Scratch's operator blocks, and set the ans variable to the result of the operation.Addition |
Subtraction |
Multiplication |
Division
When the operator is /, we know we are doing division. However, we can only divde when divisor is not zero, so we add an extra check:Division with a check for valid divisor |
Power
Scratch does not have an operator block for the power operation so we are going to work around this. As we know, the power operation simply means a string of multiplication on the base number e.g. 2^6 is 2 multiplied by itself 6 times or 2*2*2*2*2*2. 9^3 is 9 multiplied by itself 3 times, or 9*9*9. Anything to the power of zero is 1 e.g. 6^0 = 1, 541^0 = 1.Repeated multiplication to do power arithmetic |
At the start, ans is 1 After loop 1 of repeat block ans is 1*9 = 9 After loop 2 of repeat block ans is 9*9 = 81 After loop 3 of repeat block ans is 81*9 = 729 |
Suppose if num2 is zero, then the repeat block repeats for zero times, meaning that no further multiplication is done at all, and so ans remains at 1.
Invalid operator
If after comparing against all our five operators we cannot find one that matches the input, then we set ans to err.Error when there is an invalid input operator |
Step 4: Happy reveals the answer
By the end of the script, all that Happy does is to say the the value of ans. If it isn't an err value, then switch Happy's costume so that it looks really happy to be getting an answer. If it is an err value, then Happy remains real serious and says "Oops, I can't calculate this!"Happy saying the answer |
Sunday, December 11, 2011
Three ways to program falling objects in Scratch
Hey, folks! Of late, our projects have been using a lot of scripts related to falls; we used the same script in making Scratch Cat jump and fall. We also had a programming lesson on falling, and the script template includes landing too.
In this post I am going to wrap it all up by discussion three different ways to program falling objects. Take a look at this project:
The three ways to programming falling objects are:
The glide_secs to x:_y:_ block is an instruction on its own. This means that until the gliding is done, there is nothing else we can ask the sprite to do in the same script.
If we do...
...it means that the sprite will glide all the way down, and then make a 1-degree clock wise turn. This is unlike the second example, where we snapped the turn clockwise_degrees block to the change y by_ block, and have both movements occur at every loop.
To make the sprite turn as well as glide, we will need to use this script combination:
There we have it, three ways to make objects fall in Scratch. Feel free to experiment with the variables and see the difference.
In this post I am going to wrap it all up by discussion three different ways to program falling objects. Take a look at this project:
The three ways to programming falling objects are:
1. Falling with gravity
We have discussed this in great detail in the tutorial on falling simulation. The main point about this script is that we always change the sprite's y position by a certain value, velocity, at every loop. velocity's magnitude increases at every loop, so the sprite appears to fall faster and faster as if pulled by gravity. Changing velocity gives the effect of stronger gravitational pull, and the sprite accelerates even faster. Go on, test it by changing velocity's value.Script to fall with gravity |
2. Falling by changing y with a constant value
In this script, we change the sprite's y position by the same value at every loop (we put this value in the variable constant in our script), so it does not look as if the sprite is falling under gravity. It is merely moving downwards at a constant rate. Increasing constant will speed up the sprite's movement downwards.Script to fall with constant y change |
3. Falling by using the glide block
The glide_secs to x:_y:_ block lets up specify a specific position that we want to move the sprite to, and the time it takes to get there. Since we are using it here for a fall, we really only want to move it to a smaller y position. Our x coordinate remains the same. The glide_secs to x:_y:_ block moves the sprite by a linear change, so it really is just like changing y constantly. I have set the glide time here to keep pace with the second example. You could experiment with other values.Script to fall using the glide block |
If we do...
Script to turn after gliding |
To make the sprite turn as well as glide, we will need to use this script combination:
Script combination to glide and turn at the same time |
Sunday, November 13, 2011
Project: Run, Scratch Cat, Run!
Hello! Hope you have had some fun with last week's project, also our very first project to have user interaction via the microphone. You may also have read the tutorial on programming falling objects. This week, we will explore interaction with the keyboard. We will see how to program a character to run and jump. The final program is below. Use the left and right arrow keys to control Scratch Cat. Hitting the spacebar will make it jump.
Once you have downloaded the project file you will notice that the script is short! There are really just two main behaviours we want to program and they are: Running and Jumping. Let's begin:
Click the Scratch Cat sprite and put in these blocks of code:
The go to x.. and y.. block merely places Scratch Cat at coordinates (0, -80) at the very start. The more interesting bits lie in the forever loop block. What it says is "forever (or always) look out for the left and right arrow key presses". If the right arrow key is pressed, then "make Scratch Cat face right and move it Cat 10 steps forward". Similarly, if the left arrow key is pressed, then Scratch Cat should face left and move 10 steps to the left.
Run the script now and you should be able to move the cat left and right with the arrow keys, as if it is skating. That is not what we want. We want it to look like it is running. We will fix this later after we have programmed it to jump.
Currently, notice that Scratch Cat stops as soon as it reaches the left or right edge of the stage. We will add in a script to "roll up" the screen such that when Scratch cat reaches the right edge it continues to the left edge and vice versa:
Run the script, move Scratch Cat to an edge and watch the difference.
Now, on to the next step:
The blocks above says that if Scratch Cat is on the ground, we set its falling velocity to 0.5 to cancel out the work by gravity. this makes sure that it lands on the ground, and not through it. Now we slip in a couple of blocks to make it jump:
With these blocks, when we hit the spacebar the cat jumps as its y position is changed by the jump velocity of 10.
The only thing missing now are the running legs. We will do this by alternating the costumes. Note that we only want Scratch to move its legs while running on the ground and not while its jumping in the air, so we slip in controls for this in the if y position < -80 block (i.e. if it is on the ground):
And we are done. This is the final script for keyboard interaction, after adding in all the code that we have discussed:
There you go! You have just programmed Scratch Cat to run and jump with keyboard controls. Congrats!
Note: if you have downloaded my project you will notice that I have used variables to store my values. If "variables" sound alien, you may go without them for now. We will have a tutorial about them soon.
Once you have downloaded the project file you will notice that the script is short! There are really just two main behaviours we want to program and they are: Running and Jumping. Let's begin:
Step 1: Program Scratch Cat to run left and right
Let's start with a new program. We have the default Scratch Cat and a blank Stage. We paint a black strip on Stage with the Paint Editor. That's our floor.Click the Scratch Cat sprite and put in these blocks of code:
Code to move Scratch Cat left and right with the arrow keys |
Run the script now and you should be able to move the cat left and right with the arrow keys, as if it is skating. That is not what we want. We want it to look like it is running. We will fix this later after we have programmed it to jump.
Currently, notice that Scratch Cat stops as soon as it reaches the left or right edge of the stage. We will add in a script to "roll up" the screen such that when Scratch cat reaches the right edge it continues to the left edge and vice versa:
Makes sure that Scratch Cats "rolls over" from edge to edge |
Now, on to the next step:
Step 2: Program Scratch Cat to Jump
Jumping essentially involves falling. Think about it. As soon as our feet leave the ground, we are already acted upon by gravity. The reason we are able to leave the ground is because the force we muster in our jump is greater than that of gravity. Nevertheless, due to gravity, our velocity decreases all the time as soon as we jump. Here is how we will translate this in Scratch: We add in the code for falling first. Refer to the tutorial on programming a falling object in Scratch for a better understanding of this script.Blocks added into the script above to simulate fall |
Blocks for jumping |
The only thing missing now are the running legs. We will do this by alternating the costumes. Note that we only want Scratch to move its legs while running on the ground and not while its jumping in the air, so we slip in controls for this in the if y position < -80 block (i.e. if it is on the ground):
Blocks to change costumes, giving the impressing of running |
Final script to make Scratch Cat run and jump with the keyboard |
Note: if you have downloaded my project you will notice that I have used variables to store my values. If "variables" sound alien, you may go without them for now. We will have a tutorial about them soon.
Sunday, November 6, 2011
Programming falling objects in Scratch
How can we write Scratch scripts to simulate falls? In a recent project we programmed a falling ball. Here, I am going to explain it from a different angle (see and download this project at scratch.mit.edu),
Let's do a little thought experiment. What is the simplest way to make an object fall? We could start by constantly changing its y position, like so:
We could put the value of this change in a variable (we will just call this variable v) and our code would be like this:
If we run this script, the first thing we'd notice is that the fall is very unnatural. This is because the object is falling at a constant rate. It moves downwards by the same distance at every loop iteration. A fall in the real world is not like that - a falling object in the physical world moves faster and faster downwards all the time. To simulate this we simply add a statement block to increase v by a small amount at every loop:
At this point, you may be confused as to why we are changing v by negative 0.5 when previously we had mentioned we wanted to increase v. The negative sign denotes that the direction of the change is downwards. We increase the magnitude of v by 0.5 downwards, and that is equivalent to changing v by -0.5.
That was actually all the code we need to simulate a falling object.
The scientific explanation for this is that the ground exerts a force equal to the gravitational force on us. The two forces cancel leaving us stationary, since there can be no further movement without a force.
We can use the same concept in our script. We insert statement blocks to cancel out the falling distance (i.e. the v variable) when the object is on the ground.
I will suppose that when our object touches the ground, its y position is -80. So I will use the condition if y position < -80 to determine whether the object is on the ground. We could of course use other means, like the sensor blocks for example.
Here is the complete script:
What simply happens now is that when the object lands, we set v to a positive value of the falling displacement i.e. set v to 0.5. In the very next statement block, v is decreased by the same amount (i.e. change v by -0.5) leaving it to result to zero. When the program later executes change y by v it is effectively changing the object's y position by zero, and so the object stays stationary.
Let's do a little thought experiment. What is the simplest way to make an object fall? We could start by constantly changing its y position, like so:
Change y position of the object at each loop iteration |
Using a variable to contain the downward displacement |
Increase downward displacement at every loop iteration |
That was actually all the code we need to simulate a falling object.
Making the Scratch sprite land
Most of the time, we would want the object to be able to land on the ground (or something else, anything). How can we program landing with Scratch? Let's think about this again.. When we jump off a chair in the physical world, why are we able to land on the ground and not sink further in? After all, we are always acted upon by gravity, meaning that we are always pulled towards the centre of the Earth. So why not sink further in?The scientific explanation for this is that the ground exerts a force equal to the gravitational force on us. The two forces cancel leaving us stationary, since there can be no further movement without a force.
We can use the same concept in our script. We insert statement blocks to cancel out the falling distance (i.e. the v variable) when the object is on the ground.
I will suppose that when our object touches the ground, its y position is -80. So I will use the condition if y position < -80 to determine whether the object is on the ground. We could of course use other means, like the sensor blocks for example.
Here is the complete script:
Final script |
Subscribe to:
Posts (Atom)