Skip to content

Keep fractional movement in integers

  • The Craft

The aim is already calculated. Fire it with two representations of velocity and see whether they reach the same target.

Drag in the picture or use the labelled inputs and sliders. Grid squares span 25 world units. This is a mathematical model running in your browser.

Store a scaled value

The opening angle is 32.8°. Its velocity is about (2.522, 1.625) units per tick. At scale 4, store round(vx × 4) = 10 and round(vy × 4) = 7. Decoding gives (10/4, 7/4) = (2.5, 1.75). Those values describe a slightly different direction and speed.

Fire without changing the angle. The fractional reference hits; the scale-4 path misses, passing 8.41 units from the target centre. Now choose scale 256 and repeat. Its smaller rounding error lets the fixed-point path hit. More precision is useful here, but costs a larger stored value.

Position needs the same scale

Begin stored position at zero. Each tick, add the stored velocity directly. After three ticks with stored X velocity 10, stored X position is 30. Divide by scale 4 only when interpreting or drawing it: 7.5 units. Rounding the position to a whole world unit after every tick would discard the fraction we meant to keep.

At scale 256, what does stored velocity −384 represent? Where does it move from zero after four ticks?

Show the explanation

−384 / 256 = −1.5 units per tick. After four ticks, stored position is −1536, representing −6 units. Negative values use the same scale.

State the limits

We round halves away from zero, including negative values. At scales 4, 16 and 256, velocity fits a signed 16-bit integer (−32,768 to 32,767); position fits a signed 32-bit integer. Scaling increases precision but reduces the range available in a fixed width. At scale 256, signed 16-bit position would reach only about ±128 world units, so it would not cover this range.

This browser model stores the bounded integers exactly using JavaScript numbers. It does not emulate overflow. The reference also uses finite floating-point precision; it is not exact real-number arithmetic. We quantise velocity only, with no angle table. Timing, lookup tables and native instruction costs are separate questions.