In this video,
you will use a variable
to keep track of the number of hits a batter gets.
In this case,
which will change each time
the batter successfully hits the ball.
First, create the variable.
Click Make a Variable.
Name the variable something that makes sense,
More than one sprite will need to use the contents of Hits,
so keep For all sprites selected.
In the top-left corner of the stage,
you should see an orange box labeled Hits.
It shows the current value stored in the variable Hits.
At this moment, it's 0.
A few new blocks for interacting with the variable
have also appeared.
The value of Hits should change
each time the baseball touches the red, swung bat.
Drag the Change Hits by 1 block,
into the If Then block.
Click the flag to test the game,
then hit the ball.
Here comes the pitch,
it's outta here!
Now you can see that the value of Hits has increased!
the batter only hit the ball once,
and Hits increased by more than 1!
What's going on?
If the baseball touches the red bat for too long,
the number of hits keeps increasing,
because the loops run faster than the bat can change back.
To fix this,
place a Wait block from the Control menu
inside the If Then block.
To figure out how long to wait,
click on the bat's sprite to check its code.
Notice that the bat is red for 0.2 seconds,
so enter 0.2 seconds in the Wait block.
Test the game again.
When you click the bat,
it may switch the scripts over to the bat's sprite's code.
If this happens to you,
just click the baseball again to keep programming it.
The number of hits now goes up by only 1,
but it didn't start counting hits from 0.
To fix this,
drag out a Set Hits to 0 block
and place it at the beginning of the program,
just under the When Flag Clicked block.
Click the flag to test the game again.
This time, Hits starts at 0
and increases by 1 when the bat hits the ball.
Did you notice that there were lots of minor problems
to tweak in your program?
These are called bugs, and as you fix them,
you are debugging your program.
This is an important step in programming.
Computer scientists make mistakes all the time,
so stick with it as you tweak your code.
In the next video,
you'll add Analytics to your project.
Sign in to track your progress and earn badges