Unit Math: Flipping and Looping

There’s a few common problems I come across in game programming that are solvable with a set of if statements. Things like looping values or determining if a number is positive or negative. I was always  a little uncomfortable taking out multiple lines in a program to do something that felt so simple; why shouldn’t I be able to do it inline where I need the result of the calculation? Here are my solutions in pseudo-actionscript:

The latter problem, getting the sign of a number, is easily solvable by dividing it by an absolute value’d version of it’s self:

sign = mynumber / Math.abs(mynumber);

I also had the inverse of this problem,  generating a signed coefficient on the fly. Again, easy enough with some if thens and a random number, but why not do it all in one line without any flow control?

sign = 1 - math.round(math.random()*2);

Lastly, the problem of looping values. You want to step some number up by an incrementor each frame, and if it’s above a certain value, loop it back down preserving the remainder. Easily done with our friend the Modulo ( % ) operator:

myCounter = ( myCounter + increment ) % maxValue;
This entry was posted in Science, Work. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s