People are generally put off by trigonometry because it brings back bad memories of high school. I actually love it because it allows me to do really fun things when I'm programming! Animation can be a really good way to teach trigonometry and show how its concepts are really useful outside of the classroom.
Let's start with a simple idea for an interactive animation. Say you want to have an arrow that always points at the cursor on the screen. Sounds like a job for trig! Hopefully you remember SOHCAHTOA
from high school, where you use the length of two sides of a triangle to compute the sine, cosine, or tangent of an angle. In this case, we know the adjacent and opposite sides of a triangle! We know the location of our arrow, and we can use JavaScript to figure out where our cursor is in relation to it. The opposite and adjacent sides of the triangle are the difference in x and y, or dx
and dy
if you want to use the fancy calculus terms.
You can see this in action in the above Codepen. If you look at the JavaScript, you'll see that I also need to make transform the result of the touchmove
and mousemove
events because the origin of the animation element is not the same as the origin of the page.
Now we have our triangle ready to go, so we can rotate the pointer. We remembered our SOHCAHTOA
, so we can get the tangent of the angle with our dy
and dx
. BUT - we don't want the tangent of the angle! We want the angle itself. In order to get that, we need the arctangent function, which means the inverse of the tangent. In Javascript, you need to use the Math.atan2
function to calculate the angle. If you use Math.atan, it will lead to much heartache. Just try it.
That gives us the angle and we converted it to degrees, so we're done, right? WRONG. If you look carefully at the value for the angle in that Codepen, when we're right above the pointer it's telling us the angle is -90 degrees. You would expect that in that location, the pointer shouldn't be rotated at all. There's two different ways we could fix this. One, we could redraw our pointer so it usually points to the right. Or two, we could offset the angle. Let's do option two because adjusting angles is something that comes up a lot depending on the assets you make or receive from a designer. This is pretty easy to fix by adding a constant 90 degrees to whatever the computed angle is. Then we us CSS to rotate our triangle, and we're done!
TADA! Perfect. This concept comes in handy for simulating two objects bouncing off one another, and my favorite - creepy moving eyes.
Top comments (0)