Building an imaginary triangle
The monkey tower only shoots up because you haven't written any angle finding code. Yet.
To change the direction the monkey fires you are going to need to find the angle from the monkey tower, to where you pressed on the screen.
To find this angle, we draw an imaginary triangle connecting the monkey and the target, and calculate the length of the sides.
> Continue editing the script you've created on the monkey. You will be modifying this code:
The diagram below shows how we calculate the horizontal side of the triangle. We subtract the x position of the monkey from the x position of the target (where you pressed).
Observe that:
horizontal distance = target x - monkey x = 5 - 2 = 3
Remember the script you made was on the monkey. In this script we refer to the monkey as myself
and the target as the mouse.
Now let's code it.
> Open Sensing and drag x position of mouse
somewhere into the work space.
> Then open Operators and the drag the numeric +
block into the work space. Click the +
and change it to -
.
> Drag x position of mouse
into the left side of the subtraction block.
> Open Transform and place x position of myself
in the second slot of the -
block.
Now you will save the horizontal distance as a variable. We're going to call the variable dx
because it is short and stands for distance on the x axis.
> Open Variables and drag set true/false i to __
the work space.
> Click on i
and rename the variable to dx
.
> Click on true/false
and change it to number
.
> Then connect the block above the broadcast "shoot"
block.
> Drag your subtraction blocks inside of this variable block. Your code should look like this:
> When you are ready to continue, click NEXT STEP below.