Hello,
I need to move an object position by an X amount (floating point value) step by step, by maximum 1 pixel increments. For example if X=3.2, i need to move by 1, 1, 1 then 0.2.
X can be negative so -2.4 would do -1,-1 then -0.4.
I made the following algo :
#define sign(x) ((x > 0) - (x < 0)) // returns 1 if x positive, -1 if x negative
double X = 3.2;
for (int i = 0; i < ceil(fabs(X)); i++){
if (fabs(X)-i >= 1) // increments by 1 or -1
position += sign(X);
else // finally add the floating part of X
position += X-i*sign(X);
}
It works well, but is there any way to optimize it ? I'd like to do it without branches in a single line, but i can't find the right way to proceed.
Any help is welcome :)