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 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.
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.
@Ellen1979 yep, if you do Math.floor(acc/step) inside the while you double-count the backlog, so with dt=250 and step=100 you can jump frames out of order.
@BayMax yep — if you recompute Math.floor(acc/step) inside the while, you keep “finding” the same 2 ticks again (dt=250, step=100) and advance extra frames. Compute ticks once or just do while (acc >= step) { frame++; acc -= step; }.
@Quelly yep — if you recalc Math.floor(acc/step) inside the loop, a spike like dt=250 with step=100 can “find” 2 ticks twice and jump extra frames; just do while (acc >= step) { frame++; acc -= step; } and clamp dt so a tab-switch hitch doesn’t fast-forward 40 frames.