Epic failures in the game development field.

This blog covers funny/weird issues and bugs from games that happened during development.

Send your own contributions to igetyourfail at repi.se (can be anonymous if specified)

Saturday, July 4, 2009

For those times when (int)(v + 0.5f) just isn't enough


inline int MyMath::floatToIntRounded(hkReal value)
{
const hkReal lowerWhole = floor(value);
const hkReal upperWhole = ceil(value);

if((value - lowerWhole) < (upperWhole - value))
{
return floatToInt(lowerWhole + MY_EPSILON);
}
else
{
return floatToInt(upperWhole + MY_EPSILON);
}
}


(Thanks Dan)

2 comments:

Nissassa said...

Oh my goodness.

Fabrice said...

Indeed, "(int)(value + 0.5f)" is not enough, because it doesn't round negative numbers properly. The "floatToIntRounded" function is overcomplicated, but it works (if you drop the MY_EPSILON, I don't know what this one is for) :)

Anyway, the proper way of doing it is "(int) floor(value + 0.5f)" for a round towards zero (the usual way), or this for rounding away from zero: "(value > 0.0) ? floor(value + 0.5) : ceil(value - 0.5)"

Followers