Hacker News new | past | comments | ask | show | jobs | submit login
Gamedev Tutorial: Trigonometry Basics – Sine and Cosine (allenchou.net)
287 points by mariuz 85 days ago | hide | past | web | favorite | 74 comments

I can remember that I was introduced to sine and cosine through game programming before it was discussed in school.

Particularly I was trying to make games with Pascal and Assembly on an 80386. Asphyxia tutorials. No Stack Overflow, no Khan Academy, Wikipedia, in fact no Internet or even BBS at all. I feel nostalgic towards this time, but I guess that those feelings are more attached to the curiosity of an analog child being introduced to the digital magic.

> I can remember that I was introduced to sine and cosine through game programming before it was discussed in school.

I was introduced to it slightly after I was in school, but unlike school, gamedev is what made me actually understand it. Then the whole trigonometry, and basics of vector arithmetic and matrices. School for me was boring repetition of arbitrary tasks forced top-down by unpleasant people. Wanting to make my own game, that gave me huge motivation.

(Then I went to university, and on the first year's physics lab, I was asked to solve something on a whiteboard. It was a simple thing involving a vector cross product, so I proceeded to write out the formula and calculate the result. TA looked bewildered and asked me what the hell am I doing? Turns out, I was supposed to first do a whole dance around base vectors and 3x3 matrices to derive the appropriate formula, which I simply memorized when I was 14, having implemented it in C++ half a dozen times. Turns out, gamedev-driven education can leave you with holes in theory.)

Re your parenthetical story,

So like, the TA asked you to compute


and you jumped straight to

<2x6-3x5, -(1x6-3x4), 1x5-2x4>,

without the intermediate step of

| i j k |

| 1 2 3 |

| 4 5 6 |?

Or did you begin by computing the angle between the two vectors, so as to use the sine formula for cross product? Either way, I can certainly understand how your classmates (and TA) would be bewildered (especially if the two vectors were such that it wasn't immediately obvious what the angle between them was).

The first one. I jumped straight to the component-wise formula. TA expected to see the matrix you wrote above (except AFAIR transposed, but I might recall wrong).

I understand why TA didn't like it, though back then I wasn't happy that my short and "obvious" solution wasn't received well.

I remember playing around with these weird sin and cos functions whose return values seemed to lack any readily discernible pattern. After some experimenting I ended up plotting something like

and was delighted to realize that the coordinates traced the arc of a circle! Not a long time earlier I had wondered how to write a program that displays an analog clock… The connection to right-angled triangles was revealed to me only later, although in retrospect they are obviously two sides of the same coin.

I made a whiteboard robot to teach/experiment those equations. It's fun to fill a whiteboard with patterns and let people wonder how they were made: https://sites.google.com/view/wbr

That's my story, too - learned about sine and cosine by playing around with plotting the results in Applesoft Basic. Wasn't until the following year that I learned what they're for in Trigonometry class.

"analog child being introduced to the digital magic."

In high school, my electricity teacher made us draw the sine waves of monophasic and tri-phasic (if that's what it's called in English?) voltages manually by drawing into a Cartesian arrangement and projecting onto a line diagram, much like the animation about halfway through the article. It was tedious and it seemed very repetitive to draw the various variations, but in later years I started to understand its relevance (also with regards to the relation between current, voltage and power). Just in general it gave me such a good example of the relationship between the geometry, trigonometry and calculus involved, much better than the canonical speed/distance example ever did (for me). There are only a few core concepts I learned in high school that I still use often, and this is definitely one of them.

That'll be single-phase and three-phase for your enkelfasig en driefasig :)

Yeah that makes much more sense, I knew something was off :)

I really liked your phrase: "analog child being introduced to the digital magic".

I don't know if children in today's generation can at all be called as 'analog children'? And that plausibly is not good, overall.

That's quite an assumption. I really don't know if they are any better, worse or just different because their environment is different. I really don't like dissing things just because they've changed. Can you really summarise an entire generation so easily?

Sorry, my intent was neither to diss nor to summarise trivially; thanks for pointing it out and I need to put my thoughts in a better way.

It's inevitable that children today have more contact to digital technology in all its forms. This may have disadvantages.

But it's certainly not avoidable.

The best that parents can do is to try and teach and encourage children to focus on healthier stuff. To not be slaves to their mobile phones. To have empathy. Easier said than done though.

> But it's certainly not avoidable.

It certainly is avoidable. The difference between my friends who are very conscious of the exposure they give their children to TV, phones, tablets, etc vs those who don’t is striking.

Case study A: a friend who lives with her 6 year old son in a tiny Paris apartment. She has a laptop for work and an old phone she uses for WhatsApp/basic tasks, and that’s it. When I spent a few days at her place last winter, the kid helped us cook, we played board games after dinner, and he was really excited to go to the park the next day.

Case study B: San Francisco friends who let their kid use an iPad pretty much any time there is any chance the kid might be bored, moody, etc. She is pretty much addicted, and it’s quite hard to get her excited about anything else.

The 6 year is probably in kindergarden or starting elementary school. You can bet his class mates / potential friends will soon all have smart phones and converse mainly through online groups.

It's hard to say if at some point the disadvantages of limiting screen use is outweighing the benefits. Worse, if children already use social media heavily, stripping them of access during the school hours (or longer) will actually increase their anxiety levels. Children's social dynamics are tricky, especially for adults, and a lot can go wrong.

In my youth I wasn't spending so much time with a computer because it was my free choice. I lacked the social skills to make friends and was bullied heavily through my entire school life.

Next problem: To entertain a child without iPads requires a lot of time and conscious effort, which not all parents can spare, despite their best efforts. Instead of iPads, especially with preschool children, you'll see parents give them some food item when they need to be still for a time (bus, train etc). That's not necessarily a better solution.

Nor is letting them cry all the time because children at such ages can't control their focus and impulses for a meaningful amount of time.

Denthor of Asphyxia!

I didn't remember what it was by read those back in the early 90s as well, learning to program on a 486 with an early SVGA card. I think I downloaded them on a trial of AOL, my parents wouldn't/couldn't pay for AOL but I sucked all those tutorials down when I had a chance.

I was taking Pascal in school but learned a ton more from those tutorials. I wrote an asteroids type game and got tons of eye rolls from the teacher as the other students were playing my game after I shared the source. I had done the whole years curriculum in a month or two and then sat there and wrote games in class. The teacher didn't really care as I'd just about matched his knowledge by the middle of the year. He was a great teacher, had a PhD in math which was pretty darn rare for high school.

Those tutorials had a significant effect on my chosen career path.

I ended up deriving sin and cos myself. I was trying to make a Spacewar-style game and knew I needed to make the ship move depending on how it was rotated. Plotted a circle on squared paper and tried to figure out the coordinates at the circumference for all the angles I was using.

Quite a surprise when I was finally introduced to trig at school and found out it had a name!

I was utterly confused by trigonometry in junior high, it seemed to be some kind of secret language I had missed the sacred initiation rites into. And everyone seemed to treat it as exactly that--meaningless esoterica.

And then one day someone explained the high-level point to me: "Of the six quantities of a triangle (three angles and three sides), given any three of them, at least one of which is a side, the other three are automatically nailed down." Suddenly a switch was flipped. After that, the rest is just details that write themselves.

Indeed, anytime I move something on the screen at an angle for a distance, I have to do a quick check to remember whether the horizontal distance is sin or cos. I do this probably half a dozen times a month. (I'm not a quick learner.)

I was kind of surprised that the article used circular motion as its main motivating point, since I feel like just moving at some angle is so much more common.

I remember making a simple inlined asm function that called a little known x87 function fsincos that returns the sine and cosine of an angle. I seem to remember that it only took a few extra clock cycles to get both answers. This was really helpful when building matrices (in the mid '90s).

What an interesting and strange childhood you must have had to be writing games in Pascal before you heard about cosine. Either your schooling was great or terrible!

Maybe it's not the schooling. I went through a similar experience, because I started programming when I was 7 years old. By the time I had learned enough to want to try to make a game, I had taught myself Turbo Pascal, but I still wasn't of an age to learn trigonometry in school.

I had undiagnosed ADHD and was bullied all throughout my school years. So I had plenty of time.

And it really doesn't take much to learn programming in class 5 or 6...

I believe my teachers were pretty good, overall. At least as good as can be expected.

The first sentence is the same for me but to just pick up programming when you're 11 or 12 by yourself seems crazy! I'm sure you had a mentor or an older friend or some adult that at least exposed you to the concept.

I remember vaguely a course on Basic on Amigas. But other than that, I didn't really have mentors or peers. I believe I learnt QBasic from a book, later Turbo Pascal from another book and assembly from yet another.

That would probably have been enough to spark my creativity. We had a class on using word and powerpoint and typing in grade 8. America is GREAT /s

Wow, that takes me back down the nostalgia lane! Denthor's tutorials, PCGPE, Ralf Brown's Interrupt List...

Same here. First to try and get your own sine scroller working, and then to figure out 2d and 3d rotations.

Looks we need more game development in schools, as it's the most math heavy thing close to modern kids' lives.

Definitively, but it's hard to bring teachers up to speed. For one thing they often lack the particular curiosity, which may be associated to choosing the teaching path (unfortunately).

And I suspect it's also dangerous to teach coding to teachers: It's a skill that can land them much more lucrative and less stressful jobs.

Personally I think I would enjoy teaching kids math (I've done tutoring for grade school students for years), but between the pointless certifications, workplace politics, low pay, standards that force teaching to tests, harmful teacher ranking policies, and a inherit career danger for male teachers there is no way I could make such a career change. So I'll stick to tutoring two to three students a year.

Yeah I have a friend who had a math degree, taught CS and math. She got exposure to actual software dev work, realized how much better a job it is and eventually left teaching.

What’s an example of a non-stressful programmer role? Asking for a friend.

The tricky part about teaching is that it's unbounded.

I've never taught, but I remember transitioning from school to a job and it was a huge thing for me that I could keep work at work and I could start focusing on things outside without distraction. For friends that teach there's a lot of work that's expected that's not scheduled work hours (grading, lesson planning, etc). Dealing with parents is one of the largest stressors and that's almost exclusively outside of classroom time.

Depending on the particular school system, teachers can often shut out or minimize out-of-class work, but it takes a tougher attitude than many teachers have.

Also, many teachers don't think "no parent engagement" is more desirable than high parent engagement. Differences in the parents ability to engage the school (available time, money, language skills etc) contributes to social and ethnic disadvantages in many nations' school systems.

I was mostly pointing to the out-of-class work as something people who work other jobs wouldn't expect. I don't think there's a scenario where it doesn't exist and I'm a bit surprised I don't see better guidelines from either school districts or teacher's unions. It's something teacher's need to figure out for themselves. Trying to minimize that time was obvious to me as a student when I had poor teachers. Planning periods and planning days are nowhere near adequate to cover their responsibilities.

> Also, many teachers don't think "no parent engagement" is more desirable than high parent engagement.

I've never heard a teacher argue for no engagement. My point was that parent engagement is inevitable and always outside of scheduled class time. It's also one of the top complaints (along with administration and mandatory testing), so it's doubly unfortunate its unbounded.

My teachers would have shut down any parent without an extremely urgent issue trying to contact them after hours.

And I highly doubt that they got above a 40 hour work week including their lesson preparation.

But I guess expectations and regulations vary and it takes a personal strength that shouldn't be required of teachers. It's doubly sad that school systems are increasingly relying on teachers giving in and carrying more than their contractual burden.

Depends on your employer as always. But with a modicum of respect for work-hours and office climate, most programming jobs should be less stressful than teaching high school.

I'm not totally familiar with US coding/teaching jobs, and it also depends on how you deal with "stress" and the managing styles etc.

But teachers are on the front lines dealing with teenagers who are (at times) unruly, mean, sometimes outright violent, and parents will blame you for all those problems. Maybe 99% of your students are nice or well behaving, but it doesn't take a lot. I've heard quite a few stories of classes driving teachers mad. A lot of fresh teachers even drop out...

Agreed. I don't believe programming should be taught in school until late, but the use of games to bring maths alive, to give maths a relevance, would be fantastic. I, like most people, don't work in the abstract and need a framework to a) interest me in things, and b) to make them relevant. Without that it's so much harder.

I don't believe programming should be taught in school until late

Why do you believe this? Speaking for myself, I learned to program in three programming languages by 11 and I think it was very helpful.

Just IMO, programming is addictively fun and can be shallow. I think the clarity of thought and concept that maths brings is far more important. The ability to plan, to focus, to organise, and more broadly to interact with others and other life skills.

Programming does not teach those, indeed it allows the production of scrappy stuff that seems to work and is great fun. I found it hugely distracting myself in the way that social media is addictive to current kids.

I'm not explaining myself well and perhaps I'm extrapolating too much from my own case, but I hope that gives you an idea of what I'm trying to say - the very thing in programming - the bringing of something to a kind of life - is the very thing that makes it valuable to hang mathematics off, is also the thing that makes it a shiny bauble that kids/younger adults love to dabble with and be distracted by.

But your experience suggests a different POV. I may well be wrong.

"The ability to plan, to focus, to organise" is exactly what you need to build programs except for the most trivial hello world ones.

Interacting with people is also often part of it. Perhaps you make something with your friends (eg we made a class website for our school class where we uploaded photo galleries of our events and had forums and chat - all pre-facebook, around 2002-03).

By contrast math is very individual and often taught quite bad without any interaction. You learn each type of calculation task you may get on the test, memorize definitions and proofs...

And it's pretty much impossible to work on a "math project" with your friends in your free time to hone those interaction skills. Perhaps if you went to a special math focused school you could talk about math with them in your free time, in most schools that's not the case, outside perhaps discussing how to solve the test questions.

On the contrary I think a lot of the maths in school could be much better taught if they were taught alongside programming.

I used to do very well at my maths, but lost interest in large part because the maths I learned was largely disconnected from everything else I was doing despite an interest in programming.

It was first when I picked up a book on Prolog that I got symbolic derivation. The reason being that the Prolog book contained it as an example, and it was sufficiently compelling that it made me write an expression parser so that I could implement that symbolic derivation in Pascal, and the process of implementing the parser and implementing the rules applied to the syntax tree to carry out symbolic derivation brought it home in a way my teacher never did.

[Incidentally that expression parser also became the starting point for my first compiler.]

Of course programming can be distracting, because it can also allow you to explore almost any subject in more depth. E.g. what I know of complex numbers, I know because I was experimenting with fractals. What I know of graph theory is almost entirely down to playing around with parsing and compilation. And most of my understanding of trigonometry is down to toying with 3D rendering; certainly not from my maths classes in school that mostly made me loathe the subject.

There are plenty of languages that allows you to bridge a formal approach to maths with programming. But there are also plenty of ways to explore and demonstrate the concepts that will make them easier to grasp that require just very simple visualization. E.g. visualizing fractals as a means to explore topography; visualizing derivation, integration, limits, trig. For many of these presenting it as programs rather than visualization and letting students play with and see the consequences of changes has a lot of potential to make people grasp the concepts more deeply.

I understand where you're coming from. I'm often frustrated by how our industry allows software to be incredibly shoddy. But attracting kids to programming is not the same problem as making sure they grow into adults who do their job well.

Different ages have different priorities. The best way to attract kids to any activity, including programming, is to give them something fun to do. Let them make crappy stuff that's flashy and fun. If they choose to stick with it, teach them to do it well and help them unlearn the bad habits.

Incidentally, I consider bad habits to be incredibly important. Yeah, sure, you can read about how to program well, but it's not the same as having your own bad habit bite you in the ass and learning from it. It's even better if you learn bad habits and then unlearn them while you're still young and not when it might impact customers.

Just IMO, programming is addictively fun and can be shallow.

I can get that. In 1985 when I was programming my own BBS from scratch I would skip going out with friends to work on it. All that time spent on a computer as a child provided a very lucrative and rewarding career however so I don’t think I’d change any of it.

Ironically though based on your other comments in this thread I do wish I learned maths more!

I don't think those skills are particularly well developed by math for most students either.

Uh, bad post (of mine).

I agree. Maths is more important than programming IMO. But wider skills (job-related, planning, and social skills) are just as important, probably more so. But programming is an almost magical process of animating a thing. It can be too attractive, addicting, distracting...

Just my POV. I should not have posted originally without some evidence to support my claim.

Agreed, but it sounds like something that can be taught with a great teacher.

I also don't believe programming should be taught in schools, but for different reasons.

Not everyone is cut out for programming, and schools will inevitably teach it in a lowest common denominator style, where the bright kids will be bored to tears doing and redoing for loops in scratch.

Same here, with a Timex 2068.

Yikes! I use vector math (dot and cross products) to do all my game physics. Far fewer operations (two multiplies, and add, sometimes a divide). All the singularity issues were in one place, and meant something special each time, so could be dealt with in an orderly way. And could be all fixed-point or integer, no need for floating point at all.

Yes, trigonometry should be avoided whenever possible (which is much more than people often expect) in favor of vector methods in pretty much every context.

If someone wants a single number for representing a rotation, consider using the stereographic projection (instead of angle measure), which takes only 1 division to go back and forth to cartesian coordinates.

Floating point is fine for modern hardware though.

I consider it sort of a phased approach. You discover these trigonometry methods. Then you slowly intuitively understand them. Then you start to seek out new ways of expressing things (such as matrices). And you then understand why trigonometric versions have pitfalls (such as if you needed to apply something to all pixels in an image)

I enjoyed the Coding Math series a lot: https://www.youtube.com/watch?v=zm9bqSSiIdo

Here's the trigonometry playlist: https://www.youtube.com/watch?v=yAHl_kpqr-k&list=PL7wAPgl1JV...

This is great. I always had bad math teachers, so my math is like my French: Tre mal. This here is the first time I actually understood sin/cos. Thank you.

It’s “Très mauvais” :) But I agree and would love to see more work done to take advantage of animations to teach math concept (e.g 2blue1brown) game is also cool especially with unity (cf on YouTube : codeadventure)


My french is bad... Which is made even worst as I'm a French national...

Up next: Arithmetic for game developers.

No kidding.

I learnt programming about the time we started on algebra. I credit my game programming efforts with teaching me the intuition to put "text problems" into formulas and how to look at the physical or natural world.

And no, I was no genius, and even in school I was less successful than many of my peers who didn't do any programming (though quite a few did).

Vector arithmetic would certainly be useful.

[Pointer*] Arithmetics for game developers.

>There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.

- Not really sure who the original author is.

You can use sin/cos to drive leg animations procedurally. This works particularly well with things like arachnids.

Use one value to drive the forward/backwards motion of the leg. Use the other to drive the up/ down motion of the leg, although you want to clamp the range from 0.0 to 1.0 so the foot doesn't clip under the floor (although you could use realtime inverse kinematics to prevent that as well, in a game engine with reasonable IK support such as UE4).

You'll also need to negate the values for the leg on the opposing side of the body, and keep flipping those values for each pair from front to back (ie. the third pair matches the first pair, the fourth pair matches the second pair).

See https://www.youtube.com/watch?v=GtHzpX0FCFY for an example of a (hand) animated spider gait.

beautiful graphics ... thx for link .... helped my understanding of Fourier Transforms

Very nice visualizations. I used to build lots of little game-type simulations like this and I remember working my way through a very similar progression as I figured out how to draw circles and position things based on angles.

This summary was a nice refresher for me but if I were just learning it (i.e. looking for a tutorial) I would probably want more in-depth explanation along the way.

Even though I'm not really in the target audience for this, pretty good grasp on trigonometry and not really into making games, it was an excellent read!

If the author is reading this: Try removing the controls attribute on the videos and see if you like it better that way, I think I would (since they are so short and looping they are just distracting from the great animations)

No controls means if autoplay is blocked they will never start though

Aah, my bad

Oh hey my username is relevant.

I've always thought Trigonometry is taught poorly in our high schools. I've frequently seen people see the animation showing the dot going around the circle while graphing the X and Y values and suddenly having everything "click" for them, and question why that animation wasn't shown to them in high school.

There's a typo in your post where some HTML has snuck into a code block:

> &amp;lt;

I'd recommend searching for more of them :)

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact