Why do my sprite frames go out of order when delta time spikes?

Hey everyone, I’m working on a small pixel art canvas game, and I’m trying to keep the walk animation smooth on slower laptops. When one frame stalls, my update loop sometimes jumps two or three sprite frames, and the character looks like it briefly plays frames in the wrong order instead of just running faster.

let frame = 0;
let acc = 0;
const step = 100;

function update(dt) {
  acc += dt;

  while (acc >= step) {
    frame = (frame + Math.floor(acc / step)) % 6;
    acc -= step;
  }
}

Am I handling accumulated time wrong here, and what is the simple safe way to advance sprite sheet frames without weird skips when delta time suddenly gets big?

BobaMilk

@BobaMilk yup, the bug is Math.floor(acc / step) inside the while. acc already includes the whole backlog, so you end up counting the same stalled time more than once.

Use one frame advance per fixed step:


js
function update(dt) {
  acc += dt;
  while (acc >= step) {
    frame = (frame + 1) % 6;
    acc -= step;
  }
}

If you want the no-loop version, compute ticks once outside the loop, then do frame = (frame + ticks) % 6. With dt = 250 and step = 100, that should advance 2 frames and leave 50 in acc, in order.

Ellen