In this video, you’ll use “if” statements to keep the player sprite inside the boundariesof your game. Start by adding an “if” block inside the“forever” block already in this program. If statements run code if something is trueor false. Every “if” block needs a condition -- whichcan either be true or false. As you figure out which condition to use,it can be helpful to either say or think about what you want the program to do next, forexample, “IF the sprite touches the boundary, THEN do something.”
use a “touching color” block from the sensing menu.
Then, change the color by clicking on the color swatch, then on the boundary in yourproject. Great! Now the computer can make a decision:If touching the boundary color, then… In the then portion of the if-then block,program the player sprite to go back to its starting position if it touches a boundary.
To do this, use a “go to xy” block from the motion menu.
The “go to xy” block has two values, an x and a y. These numbers represent the sprite’sposition on the screen. If you move the player sprite to where itwill start, the values in the block will change to that position.
When you click and run this block, the sprite goes to the position it was in originallywhen you dragged out this block. Before you go any further, test this if statementto make sure it’s working correctly. Click on the sprite, and it should begin tofollow the mouse. If it touches the boundary, then the sprite goes to the position you setwith the “go to” block. Great! But, there is one problem. The spritecontinues to follow the mouse. Remember, the computer will do only what you tell it todo, and you didn’t tell the sprite to stop following the mouse.
Fix this bug by adding a ‘stop all’ block to the “if” statement. When this blockruns, all code in the program will stop. Now, try it out one more time.
Look at that! Now when the sprite touches the boundary, it goes back to the beginningand no longer follows the mouse. To play again, the user clicks the sprite to run this blockstack again.
This is a difficult problem! Keep trying to solve it, and don’t get discouraged if thefirst few solutions you try don’t work. Now it’s your turn:Make the sprite return to the starting position by adding “touching,” “go to x y,”“stop all” and “if” blocks.