Grif's Triangle Tutorial (AKA Lua Lesson Two)

'k so I've heard people are having some issues with triangles. That's cool, it's not the most intuitive thing. Now, the rest of this lesson assumes you know basic trigonometry; this includes "SOHCAHTOA" and not a whole lot else. So, here we go.

Now, for an example, I'm going to use my Teleporter code; it's fairly simple and only really involves one piece of code.

The code is here, stripped to absolute barebones:

http://pastebin.com/m15661553Now, notice the two functions in the Create event. This is a function DEFINITION; it's setting these functions up so that they can be called later. Also take notice of this line: "function lengthdir_x(dist,ang)".

This specifies the arguments that the function will require. So, how does this all work?

Let's reference a diagram (because diagrams are always dandy)

Now, you notice that there's a number of things going on here. First, there's a shitty rendition of a person. Second, there's a number of labelled variables, and several that aren't. So, how does it all work? Basically, using some simple trigonometry on known variables, the two functions return modifiers for self.pos that get you where you were pointing. But how does THAT all work? Quite simply, really.

Look back at the lua script. When the actor is in state body jump (using the jetpack), change the position by lengthdir_x and lengthdir_y. Both lengthdir functions have the same arguments; distance (in this case a constant of 96) and self:GetAimAngle. Since the script is run on an actor, you are able to directly access aim angle. So, with that angle and your distance (which becomes the length of the hypotenuse), you can "draw" your triangle.

So, based on hypotenuse and two angles (since one is always always ALWAYS going to be ninety degrees), how do you get the remaining two sides? Sin and cosine. Now, the math.cos and math.sin functions return a value based on the angle they're given. Since one of the function arguments includes angle, it's covered inside the function. The amount to modify X and Y to is determined through simple multiplication; again, it's all based on trigonometric principles.

So then, it's a simple matter of addition. We know how much to change the position by, and we know what the current position is, so we simply set the position again.

Any questions?