Why my sprite animation flickered
Two bats in my game flickered. Four patches missed. Measuring every art pipeline step against the source video found a lossy WebP step far worse than the rest.
Contents
Echo Bat's home screen used to show the bat small, hovering in its cave. I rebuilt it so the camera sits close on the bat while it hovers, and you swipe between the six bats you can buy. The first time I watched it on the emulator, two of them, ghost and frost, flickered. Not a dropped frame or a stutter: the wings seemed to boil, and the face shimmered as if it were being redrawn every frame by a slightly different hand.
I spent four rounds patching it, and each patch fixed something real that was not the problem. What found it was measuring every step of the art pipeline against the source video. A short version of this is the last section of the post on packing the bat's sprite sheet into a texture atlas. This is the long one, with the patches that missed and the parts that post left out.
The pipeline, as it was
Every bat's wingbeat starts as a short AI-generated video of the bat flapping in place on a flat magenta background. From there:
- Pick frames. 24 frames, spaced by how far the wings moved, from a clip of one wingbeat. For some bats that clip was spliced from two beats, and blinks were painted out.
- Key. Turn the magenta into transparency.
- Despill. Take the pink fringe off the wing edges, where motion blur mixed bat and background.
- Resize. Cut a box round the bat (about 1,000 video pixels tall for frost) and shrink it to a 360 px cell.
- Pack. Trim, dice and pack the frames into one atlas, saved as lossy WebP at quality 88.
- Play. The game plays the 24 frames on its own eased timing, and adds a slow bob, a gentle rocking, a squash and stretch on the body, and faint copies of earlier wing frames drawn behind the bat on a hard stroke.
None of this was new. All six bats went through it. The close-up was new.
Four patches that missed
One: the ping and the wing copies. I recorded the home screen on the emulator and found two things that really did flash. The sonar ping started as a bright solid disc, and at the new zoom its light filled the whole view at once: screen brightness went from 12 to 29 and back every 1.5 s. And the faint wing copies, which read as speed when the bat is small, looked like see-through wings blinking in and out close up. I dimmed the ping on home to 40% (the peak fell to 17) and turned the copies off there. The game held a steady 60 fps; the repeated frames in my first recording came from the screen recorder, not the game. Back on the emulator, ghost and frost flickered exactly as before, and it looked worst on the last frames of the loop.
Two: a hold at the loop seam. The idle wingbeat timed the way back up as two eased moves, down to level and level to the top, each slowing to a stop at its ends. So every beat the wings stopped at level for about 11 display frames, roughly 0.2 s, right where frame 23 wraps to frame 0. I made the upstroke one continuous move and added a test that fails on the old timing. Still flickering.
Three: the body drifting. The generated bat does not hover where the prompt asked. Frost drifts by up to 72 px over its video, ghost by 24. The extractor cut every frame from one fixed box, so the frame held still and the bat inside it did not: frost's body jumped up to 14 px between frames, ghost's up to 9. I added a step that tracks the body and shifts each frame to hold it in place. Between frames it then moved at most 2 px, and on the emulator ghost's biggest head jump fell from 13 px to 4. Better, but now the eye and mouth looked like they were animating on their own.
Four: freezing the face. With the body still, the face sat within 3 px of the same place in every frame, so I copied frame 0's eye, mouth and nose into all 24. It worked, in the sense that the face stopped changing. It was also clearly a patch on a patch, and still not right. What finally helped was a plain observation: the original video does not do this.
That was the useful thought. Each patch had found a real, measurable fault and fixed it, and each was a guess at the cause made by looking at the output. The video was clean. The screen was not. So something between the two was putting the flicker in, and the way to find it was to stop looking at the screen and measure each step against the video.
Measuring every step against the video
I took one frame of frost, video frame 56, wings up and face clear, and built the reference: the raw video frame, cropped with the same box the extractor uses and resized to the same 310×360 cell. Then I ran that frame through the pipeline and compared the output of each step with the step before it, as the mean difference per colour channel, out of 255. Only solid pixels counted, those above 250 of 255 in the keyed alpha, which leaves the soft edge out.
| Step | Mean error, out of 255 |
|---|---|
| Key the magenta to transparency | 0.28 |
| Despill the pink fringe | 0.11 |
| Pack into the atlas, lossy WebP at quality 88 | 2.46 |
| Atlas against the video, end to end | 2.65 |
The encoder step was about nine times the keying and about six times keying and despill together. The two steps I had spent the most effort on, because they are where the magenta lives, barely moved the picture. The step I had treated as a solved problem, because it had been measured the day before and matched the old sheet, was nearly all of it.
Two limits on that table. It is one frame of one bat, and I did not repeat it for ghost. And it measures how far the encoder moves a frame, not whether it moves each frame differently, which is what would make error read as boiling rather than as a slightly soft bat. My explanation is that a lossy encoder makes its own errors for each frame's pixels, so they do not line up from one frame to the next, and at the close-up zoom the bat's face is big enough to show it. That fits what I saw. I did not test it.
Three things the table could not show
The reference was resized to the cell, so the resize itself never shows up as error. It is still a loss: about 1,000 video pixels of bat stored as 360, then scaled back up for the close-up, on a canvas that was capped at 2 device pixels per CSS pixel on a screen that has 3.
The frame picking was the second. Spacing 24 frames by wing movement, from a clip that was sometimes spliced, then replaying them on the game's own eased timing, turns the video's smooth motion into the game's idea of it. An earlier check had told me every loop wrapped from its last frame to its first as smoothly as any other step, and that was true. It compared the picked frames with each other. It never compared them with the video.
The third was the motion the game added. Bob, rocking, squash and the wing copies are all movement the video does not have, layered on movement the video already does.
The fix: four changes at once
- Lossless WebP instead of quality 88.
- 540 px cells instead of 360, and the home screen allowed to draw at the screen's full density.
- One uncut wingbeat at the video's own 24 fps, every frame in order, instead of 24 picked frames on an eased timeline.
- The game's extra motion off for these bats while they wait on home: no bob, no rocking, no squash, no wing copies.
All four earlier patches came out. With the frames taken straight from the video, the body tracking and the frozen face had nothing left to fix.
Finding the uncut wingbeat needed a small new tool. It scores every span of the video as a candidate loop: does the frame where the span ends continue the motion of the frame where it starts, with the body lined up? A simplified version of the score, not the real code:
def loop_score(alphas, body, a, b):
"""How badly frame b fails to continue frame a's motion. Lower is better."""
def held(i): # the frame shifted so the body sits still
dx, dy = body[i]
return np.roll(alphas[i], (-dy, -dx), axis=(0, 1))
# compare a short run of motion, not one pose: a-1, a, a+1 against b-1, b, b+1
return np.mean([np.abs(held(a + k) - held(b + k)).mean() for k in (-1, 0, 1)])
Comparing three frames, not one, matters: a single pose matches the wings passing level on the way up just as well as on the way down. Two filters make the result usable. A span only counts if the wings go well above and well below level, so a twitch cannot win. And it skips any span holding a blink, so the original video can be used without the painted-out copies.
It picked frames 50 to 64 for frost (15 frames, 0.62 s) and 52 to 69 for ghost (18 frames, 0.75 s). Each loop still has one cut, where the video comes back round. At that cut the body is 8 video pixels from where it started, about 4 px in the art. Gold, reworked the same way afterwards, came out at frames 43 to 59 with the body exactly where it started.
What it cost, and what it bought
Lossless costs file size. For frost, the four combinations:
| Lossy, quality 88 | Lossless | |
|---|---|---|
| 360 px | 156 KB | 467 KB |
| 540 px | 262 KB | 932 KB |
Decoded, the 540 px frost atlas is 3.4 MB either way; lossless does not change what the GPU holds, only what the download carries. Ghost, with more frames and a wider cell, came to 1.48 MB on disk and 5.7 MB decoded. About 2 MB more download for two bats, which I took.
On the emulator, home held 59 fps with frost on screen, drawing at 3 device pixels per CSS pixel: median frame time 16.7 ms over 236 frames. A full-resolution screenshot of frost showed the fur, eye and wing membranes as sharp as the video. The 282 tests I ran passed, including new ones for playback at the video's rate and for switching the bob off. The flicker was gone, and my next job was reworking the gold bat the same way.
What I cannot tell you
How much of the flicker was the encoder. The audit says lossy WebP was by far the largest error any step added. The fix changed four things together, and I never shipped the uncut 24 fps loop at 540 px with lossy compression to see whether it still boiled. So the honest claim is narrower than the headline I would like to write: the encoder was the biggest error I could measure, and the flicker went away when it and three other things changed at once.
The patches that missed are the part I would keep. Every one of them had a measurement behind it, and that was what made them convincing. Each was measured against the screen, the frame before, or the old version. The source was the only reference that knew what the bat was supposed to look like, and I only used it once I had run out of other ideas.