Please update your browser
Your browser version is not supported by this site. CS First may not work properly.
In this video, you'll use if statements
to keep the player sprite
inside the boundaries of your game.
Start by adding an if block
inside the forever-block already in this program.
If statements run code if something is true or false.
Every if block needs a condition,
which can 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.
For example, if the sprite touches the boundary,
then do something
using touching-color block from the sensing menu.
Then, change the color by clicking on the color swatch
then on the boundary in your project.
Now the computer can make a decision:
if touching the boundary color, then.
And 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, using 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's position on the screen.
If you move the player sprite to where it will 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
in originally when you dragged out this block.
Before you go any further, test this if statement
to make sure it's working correctly.
Click on the sprite,
and it should begin to follow the mouse.
If it touches the boundary, then the sprite goes
to the position you set with the go-to block.
Well there's one problem:
the sprite continues to follow the mouse.
Remember, the computer will do only what you tell it to do,
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 block runs, 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 beginning
and no longer follows the mouse.
To play again, the user clicks the sprite
to run this block stack again.
Now it's your turn.
Make the sprite return to the starting position
by adding touching, go-to-xy, stop all, and if blocks.