Login | Register

Function for changing between two or more integers

October 16, 2007, 17:52 by Victor
[loading]
-->
Sometimes when programming, no matter what language you're using, you need to have a variable that changes between two given integers based on the integer input.

For example you might have an increasing variable, which is supposed to take the value of 2 or 4 depending on what the increasing variable is. In this case most programmers would write a very ugly function that would look something like this:

If (y==2) then x=4;
If (y==4) then x=2;


If y is the increasing variable that is.

A much better solution would be to write:

x = abs(sin(90y)*2)+2;

This "one liner" will return 2 for every even value of y, and 4 for every odd. This however isn't the best part about it. The best part is that a function written like this:

x = abs(sin(90y)*k)+m

Can be changed so that it returns the values you want. Examples:

x = abs(sin(90y)*1)+0 (k=1 and m=0)
Returns 0 for even and 1 for odd.

x = abs(sin(90y)*5)+5 (k=5 and m=5)
Returns 5 for even and 10 for odd.

And so on. I hope you see the pattern: k is controlling the size of the sinus curve, and therefore the size of the returned values. And m is used to control the values, so you can receive the numbers of your choice.

Well, now you might think "why should I learn this method, when it's easier for me to just use the 'noob-way'!". There's actually a very good reason. For more complex situations, where you might want to execute three different functions, but one of them twice as often as the others it'll become quite difficult and lengthy if you're using the "noob-way". However, some small adjustments to our function and it'll work just fine:

x = sin(90x)*3+6 for example will return the following if given numbers 1 to 12:
9 6 3 6 9 6 3 6 9 6 3 6... (and it will continue like this into infinity)

Please comment with questions. I hope you got the general idea.

// Victor

Comments

Loading comments... [loading]
.
Users logged in:

game maker articles, game maker examples, game maker tutorials, gmtutorials, game maker questions and answers, game maker crash course, how to create games