Search Unity

How/when do you use Trigonometry in game design?

Discussion in 'General Discussion' started by sluice, May 29, 2015.

?

Do you use any Trigonometry in your projects?

  1. Yes, often

    20 vote(s)
    34.5%
  2. Yes, sometime

    26 vote(s)
    44.8%
  3. No, but I might start now

    10 vote(s)
    17.2%
  4. No, careless

    2 vote(s)
    3.4%
  1. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    A previous post in the scripting section kinda went overboard and off subject on the topic...

    But I think How/when is it best to use Trigonometry in game design? is an interesting subject and is worth discussing.

    So let's talk and share some snippets!
    When to you typically use Trigonometry in game designing?


    By the way, here is my post on the other thread:
     
    Last edited: May 29, 2015
  2. Fajlworks

    Fajlworks

    Joined:
    Sep 8, 2014
    Posts:
    344
    I have a small script I mostly use for arrow pointers; it goes up/down smoothly using trigonometry.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class SinusMoveBehaviour : MonoBehaviour
    5. {
    6.     public Transform target;
    7.  
    8.     public Vector3 direction;
    9.     public float force = 0.3f;
    10.     public float speed = 1f;
    11.  
    12.     // Update is called once per frame
    13.     void Update ()
    14.     {
    15.         target.localPosition = (direction * force) * Mathf.Sin(Time.timeSinceLevelLoad * speed);
    16.     }
    17. }
     
  3. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    Character animation control and anything with rotations...UI dials and knobs, tower and tank/weapons turrets, planetary orbiting. If you aren't using trig then probably you are making a 2D grid based tile game.
     
    Alverik and dogzerx2 like this.
  4. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    @Fajlworks, I have a really similar script for a simple up and down floating script.

    Code (csharp):
    1. void Update()
    2. {
    3.     if(isFloating)
    4.         transform.localPosition = new Vector3(transform.localPosition.x, (startPos.y + amplitude * Mathf.Sin(speed * Time.time)), transform.localPosition.z);
    5. }
    For the ones wondering, the explanation I have is as follow:
    Note: that this definition is not from me, I can't remember where I picked it up thought.
     
  5. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    You can also think of trig as a transform between two different domains. Cartesian coordinates are the domain of x and y, while radial coordinates are the domain of theta and r. Each domain has its uses.

    For example, if I were calculating collisions between objects,I might prefer to be in the radial coordinate domain so I can make use of the law of reflection to simplify incident angle calculations. However, when I need to tell unity what to do,I will have to switch back to Cartesian coordinates so I can work with Vector2.

    There are lots of other uses for the radial coordinate domain, and mine is actually pretty poor. Anyways, trigonometry is the "gateway" between these domains.
     
    dogzerx2 and Fajlworks like this.
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Some random uses.

    Simple feild of vision calculations for AI rely on trig.

    The sin wave looks pretty nice. I'll often use it for enemy movement.

    Various vehicle controllers that apply torque depending on the angle between the heading and the current velocity.

    Calculating euler angles for various reasons.

    I'm sure I use trig a lot more all over the show. Half of my notes have soacahtoa written somewhere on the page. So I must use it for something.

    But it's such low level math that it's like asking what do you use addition for. I use addition all through my scripts. But coming up with examples seems stilted and forced.
     
  7. ensiferum888

    ensiferum888

    Joined:
    May 11, 2013
    Posts:
    317
    I use it to determine the position of a wall segment when I build walls in my game. It feels like the stronghold way of building walls. We start from the initial position then get the mouse position over the terrain, clamp it to the nearest 45 degree angle as I only allow building in 8 directions. I first get the end node using cos and sin:
    Code (CSharp):
    1.         private Vector3 GetClampedPosition(Vector3 start, Vector3 end){
    2.                 float distance = Vector3.Distance(start, end);
    3.                 Quaternion qRot = Quaternion.FromToRotation(Vector3.right, end - start);
    4.                 Vector3 eul = qRot.eulerAngles;
    5.                 float angle = 45* (int)Mathf.Round(eul.y / 45);
    6.                 float xEnd = start.x + distance * Mathf.Cos(angle * (Mathf.PI / 180f));
    7.                 float zEnd = start.z + distance * Mathf.Sin(-angle * (Mathf.PI / 180f));
    8.                 return new Vector3(xEnd, groundLevel, zEnd);
    9.         }
    And then I use Pythagoras to get all the nodes from the start point, to the end point:
    Code (CSharp):
    1.         private List<Vector3> GetPathFromTo(Vector3 from, Vector3 to){
    2.                 List<Vector3> newList = new List<Vector3>(50);
    3.                 float lerpIndex = 0f;
    4.                 float a = Mathf.Abs(from.x - to.x);
    5.                 float b = Mathf.Abs(from.z - to.z);
    6.                 float c = Mathf.Sqrt((a * a) + (b * b));
    7.                 float lerpIncrease = 1f / (c / 2f);
    8.                 while(lerpIndex <= 1f){
    9.                         Vector3 newVec = Vector3.Lerp(from, to, lerpIndex);  
    10.                         newVec = getNearestNode(newVec);
    11.                         if(!newList.Contains(newVec)){
    12.                                 newList.Add(newVec);
    13.                         }    
    14.                         lerpIndex += lerpIncrease;
    15.                 }
    16.                 return newList;
    17.         }
    I then add this segment to the current wall and repeat the process with endPosition being the new start position! I can then place each wall piece according to its surrounding pieces.
     
    Ryiah likes this.
  8. goat

    goat

    Joined:
    Aug 24, 2009
    Posts:
    5,182
    Trig was tough at university after basically skipping high school but it's also very interesting conceptually.
     
  9. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    While they're often both parts of the same coin, linear algebra will be used most of all. If you ever want to get into the low-level aspects of game dev, linear algebra will be your greatest asset.
     
    Ryiah and Kiwasi like this.
  10. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Did a ton of linear algebra as part of my chemical engineering degree. Never actually use it until I started making games.
     
    jpthek9 and Ryiah like this.
  11. jerotas

    jerotas

    Joined:
    Sep 4, 2011
    Posts:
    5,572
    Learned calculus in high school. Then I got a series of programming jobs for the last 16 years, including 3 as a game developer. Never used any math above basic algebra (i.e. 4 years of math I never used after high school and now mostly forgot).

    Unity makes it so a lot of the time you don't need trig either, with stuff like Lerp rotations...
     
  12. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    I can't think of a practical use for knowledge of advanced calc in video games. I guess it's because most of the cool looking stuff we fake.
     
  13. Pix10

    Pix10

    Joined:
    Jul 21, 2012
    Posts:
    850
    These days, if you're a technical artist or animator you need a good head for math, and this is before anything gets into a game. I know more than a few artists with physics and mathematics degrees - they have one hell of an edge because of it, and can do things that make my eyes boggle.

    Ten years ago, it wasn't a big ask, but now trig and linear algebra are used daily - and I'm not a natural with math, so I have to keep using it to not lose it, to paraphrase a common quote.

    Everything from writing simple art tools to character rigging and animation, to AI development - even UI design - benefit from doing things properly, and having a good math base to draw from.

    It's true that games consist of a lot of smoke & mirrors (and older artists, more than anyone, know this because we wrote the book on it), but the more you rely on smoke the more you limit what you can do, and it will likely come back and bite you in the ass further down the road, either in your current projects, or worse still your career.

    Even when there are tools/functions to make things easier (e.g. LERPs), it pays to know how to do it yourself so you know how it works and how to make the most of it. A little knowledge goes a long way - a lot of knowledge can get you well beyond the horizon.
     
    Alverik, davtam and eisenpony like this.
  14. WalkingDead

    WalkingDead

    Guest

    So all these complex stuff these guys are posting here using maths.

    This can be done in Unity without the knowledge of university maths?

    I have high school math got a B in it 10 years ago. And don't remember S*** about maths right now honestly. I don't get it though, doesn't Unreal Engine 4 have blue prints? which solves the need of requiring math and programming knowledge? If so does Unity also have this?
     
  15. Ostwind

    Ostwind

    Joined:
    Mar 22, 2011
    Posts:
    2,804
    It does not really matter what features engines offer as you will still need to understand at least the basics before you can even know what ready stuff you can use to get the things you want. It's like with basic hand held calculator, if you don't understand the basic logic behind things you don't know what buttons to press to get the result you want.
     
    sluice likes this.
  16. ShilohGames

    ShilohGames

    Joined:
    Mar 24, 2014
    Posts:
    3,023
    Blueprint definitely does not mean that you don't need math. All Blueprint does is let you do some programming related tasks with a GUI instead of text. To use it effectively, you still need to understand programming and math concepts.

    Where Blueprint is handy is when designers (non-programmers) need to build a simple quick interaction, like a door that can be opened in the environment. More complex things are actually more difficult to implement using Blueprint.
     
    Alverik likes this.
  17. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    List of all mathfz you will ever need to make games:
    -Algebra
    -Geometry
    -Linear Algebra
    -Physics, at least a general understanding so you can copy-paste formulas when needed

    All the hard stuff like figuring out formulas or finding limits... leave that to the people who aren't making games.
     
  18. WalkingDead

    WalkingDead

    Guest

    hmm interesting, I never really knew that math was necessary in creating games.

    I wonder how many people here are using Unity and are bad at maths? just imagine whats going to happen when they realize they need maths LOL
     
  19. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    I think it depends... Flappy Birds only need rigidbody.Velocity += 5. Coding the physics of FB would require more +='s and -='s but still nothing too bad.

    Coding a physics engine or fog of war with line of sight detection would take considerably more maths than cloning Flappy Bird. Like C++, elementary math skills will work fine for 99% of things but sometimes that thing in the 1% is what your project needs.
     
    Alverik likes this.
  20. WalkingDead

    WalkingDead

    Guest

    Ow so you are saying most stuff in programming only require elementary school maths? or as the British say Primary School maths? kids stuff?

    But 1% will need some advanced stuff?
     
  21. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    1% will need advanced stuff. 99% will need kids stuff. 99.5% will need intuition. Note: These statistics are not completely accurate.
     
  22. Ostwind

    Ostwind

    Joined:
    Mar 22, 2011
    Posts:
    2,804
    If with advanced you mean university etc stuff then probably less than 10% need but the thread was about trigonometry which is basically kids stuff and you probably need it now and then unless making very simple games :)
     
    sluice likes this.
  23. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    Trig is way too broad. Pythagoras theorom? Yeah, use it all the time. Sin, Cos, and Tangent? I try my best not to use them.
     
  24. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Right tool for the right job. If you game requires calculus, then use calculus. If it requires trig, use trig. If it doesn't, then don't. Not knowing the math does limit your options somewhat.

    Like in programming. Technically its possible to build every game without using an array. But its not a good idea.
     
    Alverik and angrypenguin like this.
  25. jerotas

    jerotas

    Joined:
    Sep 4, 2011
    Posts:
    5,572
    Well...Generic Lists yes. I almost never use arrays lol. But we are C# :)
     
    Kiwasi likes this.
  26. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    Brah dictionary's where it's at.
     
  27. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You get the idea. Perhaps I should have said without using a collection. :)

     
  28. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,183
    I only barely passed my math classes in high school. Despite being pretty bad at math in general I've managed to pick up the basics of geometry through a combination of experimentation, memorization and research. Having an actual use for the math is a big benefit to learning.
     
    Alverik, davtam, ippdev and 1 other person like this.
  29. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    The incredible thing about mathematics is that it is based completely in reality. Sometimes - especially in school - it is difficult to see how the abstract ideas of mathematics play any role in our lives but this is primarily a failing of the education system.

    Doing poorly in math class does not mean you are not good at math and we are finding more and more that people learn best through exploring the things they find interesting. That is why game making is so great. Some people will get nervous about pursuing a career in game making simply because they are told they need to better at math but this is just backwards thinking. That "problem" that you need to know mathematics to make games simply isn't true; the fact is that game making provides an opportunity to learn math.

    Nobody on this forum, nor anywhere in history can claim to know everything about math. If you wait until you know all about trig, linear algebra and calculus before making games, you will be robbing yourself of one of the best ways to learn.

    Also.. I think we can fake our way through a lot of things in life and, for the most part, there's nothing wrong with that. If you don't want to learn advanced mathematics, there will still be a place for you in the industry of game making. However, the question becomes more about where you want to fit into the picture. Do you want to spend your career as a junior programmer, or an assistant animator implementing other's techniques? Or do you want to push the boundaries of your abilities, create new and novel way of doing things and contribute back to your profession? The simple truth is that we need both types of people in every field.

    Personally, I like to learn and then teach.
     
    Alverik, davtam, sluice and 4 others like this.
  30. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    Builtin arrays are fastest and take the least calculation and memory overhead. Lists take something like 4X the instructions IIRC. I posted a link to some Gamasutra article on optimizing in Unity a few weeks back that explained it in technical detail. I don't like these <corner bracket thingees>. They mess my artistic code formatting..LOL..And I like to track it all in the Inspector without serializing and getting verboseness all over my pretty code structure:)
     
  31. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853

    This.. Until I started messing with Flash in the 90's and getting visual feedback I didn't get trig. My math teachers sucked and I wasn't gonna be a sailor so WTF did I need triangle calcs for (69-73). I could have not cared less how to find the center of a triangle using maths. I could pinpoint it by eye. I use to draw Marvel comic book covers in math. Now..had they divined 15 - 25 years into the future and told me i could animate superheroes in 3D using triangles I would have been all over it with rapt attention like a cartel soldier on a cash filled piñata..
     
  32. WalkingDead

    WalkingDead

    Guest

    Hey what kind of degree do you have?

    And what do you do for a living?
     
  33. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,183
    I don't have a degree. I started working towards one back in 2002 or so, but my community college tuition became much more expensive in a short period of time so I ditched the degree in favor of simply continuing my education on my own and working into the industry that way.

    I'm almost entirely self-taught having started at the age of 12 with QuickBASIC. I picked up the majority of C++ in between college semesters, Visual BASIC .NET through one class, and Java through another. While there were some benefits to the three college classes I took, the majority of it was stuff I already knew.

    I am on disability.
     
  34. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    I just feel like chipping in on the Math thing...

    As much as I feel like I haven't used some of the Mathematical knowledge that I've learned in High School for a few years afterwards.. that statement is most definitely false.

    In Mathematics class you learn more than the "low level stuff" such as algebra and trigonometry.
    To a higher level, you learn on how to solve problems. There is a reason why a lot of career such as Police Officer requires Math 436 (Basically, the highest/most important maths in High School here).

    Also, if you remember, when being evaluated in your math course, your result on a question didn't all come from your answer but how you got there. Prooving your reasoning was just as important (if not more) than your actual answer.

    Anyway, Mathematics are something powerful and even though I completely nailed my last math (436) class with a 95% grade I wish I would of taken them a bit more seriously when it was the time (and afterwards)! Now it seems like that was an eternity ago and I forgot so much... :D

    I always say that Programming are like Mathematics.. not because your are calculating stuff, but because you are solving problems. :rolleyes:
     
    Alverik, Ryiah and angrypenguin like this.
  35. Mattyy

    Mattyy

    Joined:
    Jun 12, 2013
    Posts:
    42
    Interesting question!
    I've used Math in countless scenarios and here is some from just one script of mine.
    Calculus:
    By using calculus, I was capable of constructing a 3rd degree polynomial equation by only knowing 2 key points on the curve
    Code (csharp):
    1.  
    2.             a = (y1-y2)/(((x1*x1*x1-x2*x2*x2)-(3*x1*x1*(x1-x2))) - (3*(x1*x1-x2*x2)*((x1*x1-x2*x2-2*x1*(x1-x2))/(2*               (x1-x2)))));
    3.             b = (3*a*(x1*x1 - x2*x2))/(-2*(x1-x2));
    4.             c = -3*a*x1*x1-2*b*x1;
    5.             d = y1 - a*x1*x1*x1 - b*x1*x1- c*x1;
    6.  
    This right here is a summary of papers of math.
    I've also used calculus to know the gradient of the polynomial at any certain point
    Code (csharp):
    1.  
    2.         public float gradient(float x)
    3.         {
    4.             return 3*a*x*x + 2*b*x + c;
    5.         }
    6.  
    And of course used it to find get my AI to follow the curve using Tan(gradient) to find the angle with horizontal.
    Knowledge of circle have helped me in writing this function where I can find a point lying on a circle:
    Code (csharp):
    1.  
    2.     public static float yCircle(float z, Vector3 point, float radius, bool sign)
    3.     {
    4.         return (sign? (point.y + Mathf.Sqrt(radius*radius - (z - point.z)*(z - point.z) )) : (point.y -       Mathf.Sqrt(radius*radius - (z - point.z)*(z - point.z) )));
    5.     }
    6.  
    I haven't used trigonometry as much in this script. In fact, I rarely use it. However, I've used my knowledge of vectors and planes to calculate the normals by finding the common normal on each triangle/face on a procedural generated mesh.

    Using Math isn't always a must, but it opens way more paths for you to choose. It allows you to tackle huge tasks and knock them down into way more manageable tasks. I can't imagine programming with out my math.
    Unity hands us a huge vector library so although studying about vectors helps, I don't think it's as important as knowing some calculus.
     
    Alverik likes this.
  36. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Interesting. I did both calculus and algebra right through my degree. In my day job as a chemical engineer I find calculus far more useful. But in terms if programming and game development I tend to use the algebra stuff more often.

    Part of it is the nature of Unity's simulation. It's inherently discrete and dynamic. Which makes completely solving models using calculus far less useful.

    That's just my experiance though.

    That's pretty phenomenal, if you can solve a problem with four degrees of freedom using only two data points. ;)
     
    Alverik likes this.
  37. Not_Sure

    Not_Sure

    Joined:
    Dec 13, 2011
    Posts:
    3,546
    Sadly I never took trig or calc in college, and sadder still I really suck at being a math student. It's embarrassing how bad I am.

    That said, now that I'm using algebra all the time on my own I'm finding it incredibly easy and fun when applied to games.

    Not taking trig or calc makes me feel like I'm short some tools and at this point I'm not sure how to get started using it.
     
  38. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    Unless you're working on AI or a physics engine, you only need these things to make a game:
    - Pre-algebra
    - A game engine that does all the hard stuff for you
    - Documentation

    Idk, can anyone think of an exception to this claim?
     
  39. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853

    Mostly..But dial pointer/speedometer type widgets. Getting and Setting rotations for point and click type nav. Controlling joint transform rotations when animating via code. Unity does give a robust set of tools to handle most of this stuff under the hood.. I found Mathf.atan2 to be handy in a number of situations for setting rotation angle based on position and center rotation point.
     
    Alverik likes this.
  40. Mattyy

    Mattyy

    Joined:
    Jun 12, 2013
    Posts:
    42
    Haha, I said key points because they aren't just normal points, they are the ones where the curve turns, aka gradient = 0, hence I have 4 pieces of information.
     
    ippdev and Kiwasi like this.
  41. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    This is a good place to start. It's not Unity but still related to game develop.. The theory is the same and can be applied to Unity quite easily: http://www.raywenderlich.com/35866/trigonometry-for-game-programming-part-1


    You don't need to know much mathematics to do a game outside of knowing basic equations and their orders (P.E.M.D.A.S.). You certainly do not need Trigonometry. Trig is just another tool in the toolbox. It can be useful to do many things. On the top of my head:

    -For easing/tweening
    Code (csharp):
    1. //Ease out formula
    2. float t = currentLerpTime / lerpTime;
    3. t = Mathf.Sin(t * Mathf.PI * 0.5f);
    4.  
    Source: https://chicounity3d.wordpress.com/2014/05/23/how-to-lerp-like-a-pro/
    -For finding the distance between objects. (Yes, Unity has this built in, but you might want to run your own custom method, I do..)
    -To rotate an object toward another object. (Yes There is a lookAt method in Unity, but it does not work in 2D)
    -The link at the beginning of my post, explain different reasons on when Trig could be useful.

    But depending, on your game/project: having a good knowledge of:
    -Physics
    -3D Maths
    -Probability
    -Statistics

    Can always be useful/necessary.
     
    Alverik likes this.