I always get excited when I have to use math when I’m programming something, because then when my kids get old enough to complain “Augh, math?! When am I ever going to use this?!”, I’ll actually be able to tell them, “Hey, I actually use math at work!”
Ok, so this particular time it wasn’t something for work, but it’s still math! Here’s the basic problem:
Starting with a spider at point A, swiped to point B, how do you determine a point C offscreen where the spider ends up after being swiped?
This is how I solved the problem using…GEOMETRY! If you have two points, you can calculate the slope (m) and then use the same slope equation to find a y value given an arbitrary x. Here’s the equation to find slope between two points (x, y) and (x1, y1), in case you’re too lazy to google it:
m = (y - y1) / (x - x1)
So using that, we can calculate the slope of the line we create when we swipe the spider from A to B:
m = (A.y - B.y) / (A.x - B.x)
To figure out where point C is, let’s choose an arbitrary x value for C based on the direction of the swipe, and use the same equation to solve for the y value. In our picture above, we’re swiping left (A.x > B.x), so let’s say that C.x is at a position 100 pixels off the left side of the screen, or -100. If we’re swiping right (A.x < B.x), then let’s say that C.x is 100 pixels off the right side, or screensize + 100.
So now that we know the slope and the new x value, we’ll just reswizzle the slope equation above and solve for the new y value:
y = m * (x - x1) + y1
And in our case:
C.y = ((A.y - B.y) / (A.x - B.x)) * (C.x - A.x) + A.y
I actually really loved math in school, especially geometry in 7th grade, because we got to use rulers and compasses to draw graphs. There really is a lot of math you can use when you code, so keep taking those advanced math classes, ladies!