July 29, 2014
Press Releases
July 29, 2014
PR Newswire
View All
View All     Submit Event

If you enjoy reading this site, you might also want to check out these UBM Tech sites:

On Functions
by Toby Grierson on 10/29/13 06:34:00 am

The following blog post, unless otherwise noted, was written by a member of Gamasutra’s community.
The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company.

Aspiring developers sometimes wonder do I need to know math? If you can think in terms of procedures, you can often get away with knowing little more than algebra and the boolean operators. Certainly you can cobble together a website. If you work in Unity 3D, many get away with just enough understanding of matrices, quaternions and vectors to nudge things around. No need for more, right?

But the moment you hit a hard problem, what? Give up? Or supplicate before Stack Exchange, gamedev.net, … Dear Prudence? Ouija Board?

Discrete mathematics is the star of computing what with sets, graphs (they come up a lot in “AI”) and more but let’s talk about functions. The ability to rejigger a function of your own; to solve for x; to factor it; etcetera. With a little imagination and a talent for story problems you can apply these techniques.

Let’s do an exercise. This here is a muffin:

This screenshot’s from the Turbo Slicer demo (my Unity asset I'm quite proud of); the sword is mouse controlled and the cursor drags it around to hack muffins. They’re flung onto the screen from a spawner below and gravity pulls them back down.

I tweaked the upward boost just right to fling them into the play area, but soon as I changed the gravity from -9.8 to some other figure, they would fly too high or low. And – long story short – this was not okay.

Wouldn’t it be magical if the code would just figure out the right speed? We know where we want the muffin. We know the gravity. So let’s do it.

First, we’ll create a function to yield the height of the muffin at a particular point in time.

Before I go on I’ll explain what this function means. Given the initial vertical speed i, the gravity acceleration g in the same unit of measure and the time t, we get the height h. For example, if the initial vertical speed is 5 (meters per second) and the gravity is 9.8 (meters per second square) than at 5 seconds in, the height is -97.5 meters.

Using derivation we’ll convert this from a function that gives us the height according to time into one that gives us the vertical speed according to time. Like so:

Given the same inputs as above (5, 9.8 and 5) we find that its speed is -44 meters per second. And why is that useful?

First it goes up, then down. The vertical speed must first be positive, then become negative when the gravity steers it downward. Therefore at the turning point – the peak – it will be 0. So if we assert that the vertical speed is 0 …

… and then solve for t …

… we get something magical. Given a specified initial speed and the gravity, this function yields the exact moment when the muffin reaches its peak. For our example numbers (5, 9.8) the answer is just a hair over 0.51 seconds.

If we combine that with the first function …

… we get a function with no time input. We can infer t from i and g and gain a function that tells us the maximum height H based only on the initial vertical speed and the gravity.

You see, we know the intended maximum height and we know the gravity and we want that initial speed so all we have to do is solve for i.

We place the intended maximum height and the gravity into the right hand side and out pops the intended height. Do we want to hit 5 meters up with a gravity of 9.8 meters per second squared? It needs to be flung up at a speed of 9.9 meters per second.

And I just retype it into C# …

private static float speedToReachDesiredHeight(float h)

{

float g = -Physics.gravity.y; //Unity3D stores a vector like {0, -9.8, 0}

float i = Mathf.Sqrt( ( h * g ) / ( 1f - g / (2 * g) ) );

return i;

}

… and now the code can be dropped into a project with different vertical gravity speeds and just work.

You may notice certain inputs give no sensible answer. Placing a 0 in for g gives a division by zero, or “undefined” result. This is fine; there is no single answer if the gravity is set to 0. I specifically did not let the two Gs in the lower fraction “cancel out” because that would change the function domain (the set of inputs for which it is valid).

The function’s behaviour is also not defined (in the “undefined behaviour” sense) for gravity that accelerates upward or for inputs where the requested altitude is toward the direction it’s going to fall; coping with these conditions are not in this function’s specifications. It’s simply an error to ask this question at all for some inputs.

Error handling is of course a project specific matter beyond the scope of this article.

In any case, it's an odd problem, but it's a real one. I hope this example gives some a better mental image of what all those story problems are for. Computers can offer far more difficult challenges when one wants to work on the frontiers of image processing, recognition, "AI" and others. Maths are the intellectual tools of the trade; they empower us to solve problems that can't yet be Googled. If you aim to work on the front lines, stay awake for math class.

–Toby

### Related Jobs

Activision — Seattle, Washington, United States
[07.29.14]

Software Engineer - Activision Seattle
Treyarch / Activision — Santa Monica, California, United States
[07.29.14]

Senior Environment Concept Artist - Treyarch (temporary)
Vicarious Visions / Activision — Albany, New York, United States
[07.29.14]

Software Engineer-Vicarious Visions
Sony Online Entertainment, San Diego — San Diego, California, United States
[07.28.14]

UI Programmer, PlanetSide 2

 John Wallace
 Getting out of high school, my math skills deteriorated very quickly. In UDK, it's a situation of looking up tutorials or randomly slapping equations together. Fun, but not logical.

 Dan Brown
Unless I'm missing something, g / 2g is always 0.5, regardless of what g is (except for 0, obviously). In code, that might not be completely true if there happens to be any float precision issues, but on paper that is always 0.5. With that in mind, you should be able to further simplify your equation to be Sqrt( Hg / 0.5 ).

Am I wrong?

 Toby Grierson
 Basically you are right. It can't be said that g/2g is the same as 1/2 since the domain of the function differs; that "except for 0" can matter. But here it does not: dealing with a g of 0 is _not_ in this function's specifications. What it does when g = 0 is irrelevant.

 Michael Mullins
It's really nice to see the fundamentals of acceleration covered here, but I'd advocate for dealing with a far more basic issue for people who are unfamiliar or even a little scared of this material: logical problem solving and fundamental algebraic manipulation. A late high-schooler or early college student confronting this material in a physics or calculus class has to go through the pain of solving position for velocity and acceleration using any force imbalance. What that does is show why kinematics equations look the way they do... And recognizing the pattern (x^2/2 is an anti derivative) absolutely blows the students mind in eureka kind of way. That lends greater motivation to master what's actually going on better than looking up forms. Practice (at least a little bit) makes you dig into it and it is totally worth your time, even as a newbie struggling indie person.

 Toby Grierson
 Good comment. I assumed here basic algebraic manipulation, booleans and so forth were obvious and wished to show some of the less basic things can be applied at work, but I may be wrong. I'm planning a second write-up, late next week most likely. Thanks for reading.

 Michael Mullins
 I don't think you're wrong at all, but the magic of this relationship between the qualities of motion runs pretty deep. The algebra is critical, but the importance of the relationship shouldn't be underestimated as you demonstrated.

 Ron Dippold
 Very relatedly, any programmer who doesn't understand calculus seems doomed to eventually re-invent it (badly) instead of just getting right to the solution like Toby's done here. No need to memorize the actual transforms since Wolfram can do that for you now, but if you learn the basic concepts it's amazingly useful.

 John Trauger
 It's a huge asset for a designer to be able to do the math. Design always translates into math anyway. Who better than the designer as the interpreter?

 Tande Mungwa
I'd really like to see more articles like these that deal with the fundamental mathematical concepts underlying game physics and simulation as a whole.

Question: How are the concept of limits typically used in video-game development? Excuse the naivety -- I'm a Freshman at University.

 Ron Dippold
 Limits? Well, we don't like to evaluate infinite series in real time (har), or even N terms for 40000 objects, so mostly in the pre-coding stage. - What precision do we need? This is the most important question. - Can we eliminate this calculation entirely? (1/2 + 1/4 + 1/8 + ... = 1) - Can we transform this to a lower complexity version (perhaps through Laplace transform)? - Can we approximate this to a lower complexity version that meets our precision needs? Even something as crude as a curve fit. - Can we approximate then clamp? For instance, it's surprisingly hard to avoid all instances of number / infinitesimal number = near infinite force = object near light speed, but it's cheap to clamp inertia to some max number. I would say the most common version of this in games is terminal velocity - very few games bother simulating all the surface area of the falling body vs density vs air resistance, etc. Rather they use v = a*t then clamp to some maximum velocity. To sum up, you can almost always find a polynomial that's within your precision and has the same limit as what you're trying to calculate, which is where limits are handy in the planning stage. I will disclaim that I've done physics sims, but am not a hardcore physics engine god like people working on car sims who are trying to model each tread and the air resistance over the creases in the seats. Hopefully one of them can chime in.

 Joseph Cassano
Where is the first equation coming from? It seems like you say "we'll create a function" and then just plop one down. Is it a standard physics equation I'm unaware of (like how, in simple terms, velocity is distance over time)? Am I missing something?

 Frank Washburn
 It is indeed a fairly standard physics equation. But in case you don't remember it - its derivative is also fairly standard: The vertical velocity of something over time is simply its initial velocity minus g * the time it's been in the air. So just integrate that to get to actual Y coordinates from vY. Honestly, IMO using vY is the most simple/logical starting point, but the one that OP chose is also well-known if you've recently taken physics/calc.

 Joseph Cassano
 Thanks, Frank. Although I love physics conceptually, my actual physics education didn't go too far in school, and I never took calc. I should probably start to remedy both of those things, actually. =)

 Toby Grierson
 Washburn is correct. "IMO using vY is the most simple/logical starting point" That didn't occur to me but that would have made for a better article.

 Joseph Cassano
 Thanks, Toby. The article makes a lot more sense now. =p

 Zachary Hoefler
One problem I've come across is that I'll come up with a solution like this, but have no concise way to comment it given it's basically a bunch of mathematical steps and derivation. A few weeks/months later, something like the "Mathf.Sqrt( ( h * g ) / ( 1f - g / (2 * g) ) );" in the above example is basically the functional equivalent of a magic number.

Anyone have a good (or at least not-terrible) solution?

 Toby Grierson
 What I do is write a plain text explanation of the use-case and scenario. In this case if I wanted to comment that I would basically cram a short version of the article above into a comment.

 Ron Dippold
 In the past I'd have a LaTeX or Word document in the repository that documented this (and a pointer in the code). That still seems reasonable, but if you want your derivation right in the comments you might use TeX and a pointer to http://arachnoid.com/latex/ - for example J_\alpha(x) = \sum\limits_{m=0}^\infty \frac{(-1)^m}{m! \, \Gamma(m + \alpha + 1)}{\left({\frac{x}{2}}\right)}^{2 m + \alpha} and paste that in the box and you'll get a very pretty equation. That uses http://mathjax.org to do the heavy lifting. In practice though, if there's not anything really egregious to render, I just use ASCII because it's so much easier. Something like 'given acceleration _a_ and time _t_, y = 1/2 a*(t^2)' So the first equation renders as 'h = it - ( gt^2 / 2 )' (Which Toby helpfully provided as alt text).

 Wendelin Reich
 The link (arachnoid) looked promising, but I get "This webpage is not available". Do you have an alternative site?

 Joseph Cassano
 The page (http://arachnoid.com/latex/) is working for me. Maybe it was temporarily down? I'm using Firefox on Windows 7 64-bit, if that helps any.

 none Comment: