So, I’ll have a go at this. The following assumes knowledge of basic algebra (specifially, solving equations).
Trigonometry often comes into play when we are dealing with velocity.
Imagine we have a spaceship and an asteroid. Well, let’s not just imagine. Here ya go:
Now, let’s say we want to give the spaceship an appropriate velocity so that it moves toward the asteroid. In this case, we know the coordinates both of the spaceship and of the asteroid, so we can just do some quick subtractions to get an appropriate velocity:
Other times, though, we don’t know coordinates. Instead, we have a velocity vector: We know the speed that we want the object to move, and we know the direction of the movement, expressed as an angle:
In this case, we know we want to move the spaceship at a speed of 50 and an angle of 30 degrees. We don’t have a way to express this in MakeCode Arcade natively, so we need to translate this information into an x velocity and a y velocity. This is where our trigonometry facts come into play. Remember soh-cah-toa: sine is opposite over hypotenuse, cosine is adjacent over hypotenuse, and tangent is opposite over adjacent:
sine = ----------
cosine = ----------
tangent = --------
For our triangle, vy is opposite (or across from) our angle, vx is adjacent (or connected) to our angle, and the hypotenuse (the long side of the triangle) is 50. To figure out vx, we are dealing with the adjacent side and the hypotenuse, so we know we need to use the cosine function. Rearranging the equation a bit, we get
vx = 50 * cosine(30)
Similarly, we need sine to figure out vy:
vy = 50 * sine(30)
Since MakeCode Arcade has access to trig functions, we can let our program do the calculations:
Last bit of trickery: Like most programming languages, the functions in MakeCode Arcade do not use degrees to measure angles. Rather, they use radians. Quick conversion: 180 degrees = π (pi) radians. You can see that conversion in the code above.
Now, why would we ever need this? Here’s one example:
Let’s say we have a ball and a paddle at the bottom of the screen controlled by the player. Instead of simply reflecting the ball off of the paddle, we want the player to have some control over how the ball bounces off of the paddle. If the ball hits in the middle of the paddle, then the ball will bounce straight up. The more off-center the hit is, the more sideways we want the ball to bounce. No matter which direction the ball is moving, though, we want it to move at a constant speed.
The code could look something like this:
Feel free to play around with these samples.
To learn more about trigonometry, perhaps give Khan Academy a try.
As always, if you have any questions, feel free to ask!
P.S. Yes, I have written an extension that handles some of this math for you. Check the link below for the Vector Math extension.
See all of my MakeCode Arcade games and extensions here!