Hardware Reference
In-Depth Information
Using “if” Statements to Show and Hide Sprites
As it stands now, when you play this game the new sprites that you have created so far,
such as the portal sprite, remain visible even when you change backgrounds. his is a
little confusing. You really want the portal to show only on the irst background,
Outside
, and the key to show only on the second background,
Inside
. In this sec-
tion, you learn how to add an
if…else
block to address this problem.
If
and
if…else
statements are common constructs in computer programming.
When you use an
if
statement, you are asking for a condition to be met, and
then making something happen if the condition set is true. For example:
If
it
is raining, then put up an umbrella. You can add another action for when the
condition is false using the
else
command. For example:
If
it is raining, then put
up an umbrella;
else,
wear sunglasses.
he script you create in the following steps tells the portal sprite to appear only when
background 1—the outside of the cave—is shown, and to remain hidden the rest of
the time.
1.
In the portal sprite's Scripts tab, add the control block
when
clicked
and
attach a
forever
looping control block to it.
2.
Next, add the control block
if else
inside the
forever
loop and drag the
operator block
0 = 0
into the
if
hexagon condition (refer to Figure 3-23).
3.
Place the sensing block
of
inside the irst 0 of the operator block, and add the
value 1 to the second part of the same block.
4.
Using the drop-down menus on the sensing block, change the irst value to
background #
and the second to
stage
.
5.
Finally, add the looks block
show
under the
if
condition and the looks block
hide
under
else
. Save and test your script.
CHALLENGE
What amendments to this script would you need to create to hide the key on
the
Outside
background and show the key on the
Inside
background? Try
making these changes to your script.