I often need this kind of function, for example, for understand the direction of the touches on iPhone and the only way to solve this problem it’s by using logic, like this:
int dir,distY;
distY = newY-oldY;
if (distY > 0)
{
dir = 1;
}
else if (distY < 0)
{
dir = -1;
}
I would like to know if there is an way to do it in one shoot mybey by using a mathematical method or a fashion old-school way.
Clarification, a similar example of what I’m looking for is:
i = ++i % max;
instead of:
i++;
if ( i > max ) { i = 0; }
Assuming you’re using something like C or C++ that will convert true to 1 and false to 0, you could use:
direction = (distY > 0) - (distY < 0);. You didn’t say what you wanted whendistY=0— this gives 0 (which seems like the obvious choice to me, but who knows).Of course, there’s no guarantee it’ll do any good — that will depend on a combination of compiler, compiler flags, CPU, and maybe even the phase of the moon. OTOH, I’d guess it has more chance of doing good than harm anyway.