Theory
๐ฑ 11. Sneak Past the Shark
Pufferfish sees some tasty food ahead, but she has to get past the shark to reach it! Letโs use a variable to help Pufferfish sneak past the shark. With a variable, we can change a spriteโs speed to go faster or slower. We can even use it to make Pufferfish stop immediately if the shark has spotted her. Just donโt let her get caught, or sheโll become a shark snack!
Step1
Begin a new program with Pufferfish and Shark2 sprite. Arrange them like you see here.
Step2:
Go to Pufferfishโs script editor. Drag in when flag clicked event block and a go to x: (__) y: (__) motions block to give Pufferfish her starting point.
Step3:
Create a brand-new variable like you did for the Timer in our last activity and name it โspeed.โ Add a set (speed) to (0) variable block so Pufferfish always starts with no speed. (Remember to select your new variable from the drop-down menu in the code block.)
Step4:
๐ก Adjust Pufferfish’s speed with “move (__) steps” block: Higher steps = faster, lower steps = slower โก๐ข
๐ Customize speed dynamically: Insert speed variable block into “move” block for user-controlled pace ๐ฎ
Step5:
๐ Ensure Pufferfish keeps moving: encase “move (speed) steps” block in a forever loop ๐๐ก
๐โโ๏ธ Without value changes, Pufferfish won’t move; Add events to alter speed variable’s value ๐๐
Step6:
Stay in Pufferfishโs script editor and start a new script with when (__) key pressed event block. Click the drop-down menu to select the right-arrow key. Pushing that key will make Pufferfish move forward.
Step7:
๐ผ Accelerate Pufferfish: Use “change speed by 1” block when right-arrow key pressed ๐โก๏ธ
๐ Test it out: Single key press increases speed gradually, enabling faster movement ๐ฎ๐
Step8:
๐ Introduce emergency stop: Create new script with “when (down arrow) key pressed” event
๐๐ฝ ๐ก Incorporate “set speed to 0” block to halt Pufferfish’s movement instantly โ๐โโ๏ธ
Now she should be able to swim faster and faster the more you push the right-arrow key, but she can also instantly stop in her tracks whenever you press the down arrow. Sheโs a agile little fish!
Step9
Step10
Now switch to your sharkโs script editor. Start his script with when flag clicked event. Then add a set rotation style (left-right) motion block and a point in direction (-90) motion block to make the shark face Pufferfish.
Puffer Fish Code
Shark Code
๐ YOUR TURN! Challenge yourself to:
- ๐ Incorporate a scary sound effect for each shark appearance.
- โฒ๏ธ Adjust wait timings for random shark appearances.
- ๐ก Experiment with additional movements: Up arrow for what action? Back arrow for another? ๐ฎ