Automatic Monkey Mayhem
In this chapter, we're going to teach your monkey how to shoot bloons by itself. We will use Pythagoras to detect when a bloon is within range. Our previous code will take care of the rest.
Here's our objective:
If the front bloon is in range, shoot at its position.
This is actually three objectives. We must find:
- What is the front bloon
- Distance to front bloon (Pythagoras)
- Angle to front bloon (inverse tangent)
Your monkey doesn't try to shoot on its own. It's just waiting for input. We need to get that monkey thinking for itself.
- Edit the
Tower Controller
script. - Disable or delete the
When stage is pressed with pointer
event. We won't be using it any more. - Add a
Constantly
event to the script. - Constantly call the
attackBloons
function. - In the
attackBloons
function, settargetX
andtargetY
to the X and Y coordinates of the first bloon before you callattack with: monkey
.
You should now have Constantly
and attackBloons
blocks that look like this:
Test your game. You should see your monkey throwing darts at the front bloon.
Turn on the diagnostic mode. You can see the X and Y components of the vector, but not the length of the vector itself.
Notice how you didn't need to change attack with: monkey
at all. As long as targetX
and targetY
are set, the function will be able to target that coordinate.
But the monkey doesn't know anything about range yet. It cannot hit the bloon if it's too far away. To challenge you, we're given the monkey a limited number of darts! If it runs out of darts, the invasion cannot be stopped. We must change the function so it will only fire if the bloon is within range.
Time to use Pythagoras.
- Look at the
attack with: monkey
function. - Set
distance
tosquare root
of a+
block. - In the first slot of the
+
block, insertdx
^
2
. (The^
block means "to the power of", thus ^2 means "squared". You can find^
from the dropdown menu in a+
block.) - In the second slot, insert
dy
^
2
.
Now you know the distance to the target. All we need to do is check that against the maximum range of the monkey:
- Just before the messages at the end of the function, insert an
if
conditional. - If
distance
<
128
... - Drag all three message blocks into the
if
bracket.
The conditional will only send the signal to fire if the bloon is within range.
Test your game, and see if it works.
Turn on diagnostic mode again. Now that you are calculating the hypotenuse, you should see the entire triangle.
Victory
Congratulations! When your monkeys are autonomously assaulting anomalous aerial attackers, your game is working as intended. You've just coded a tower defense game like the folks at Ninja Kiwi.
Along the way, you learned about vectors, trigonometry, and the Pythagorean Theorem. This is how the pros do it!
Good work! Try your hand at our extra challenges if you want, but for now, take a breather.