Rounding down is more complicated than I thought

Another day, another learning opportunity. While working on a platform game I noticed my characters movement was a little off. It was subtle but it seemed to move faster to the left than to the right… Very odd.

I spent a few hours going through the movement code, debugging, experimenting, constructing theories about causes, disproving my theories and generally going around in circles. Eventually I figured it out and it was kind of interesting.

Somewhere in the code when dealing with velocities I was calling math.floor(). floor() rounds down, which sounds simple. So simple that I overlooked it repeatedly while reviewing the code looking for the problem.

The problem is that velocity can be either positive or negative. It’s positive when you’re moving to the right. Negative when you’re moving to the left. If you have a positive velocity, say 2.4, it gets rounded down to 2. However if you’re velocity is -2.4 is gets rounded down to -3. When moving to the right velocity was reduced. When moving to the left velocity was increased. Bingo.

For some silly reason I was thinking of rounding down as rounding towards zero rather than sliding to the left on the number line. If you ask me whether -3 or -1 is less than -2 my first impulse is to say -1. Damn brain.

Leave a Reply