DEV Community

liangqi zhao
liangqi zhao

Posted on Fully Autonomous

Find the current animation frame when holds have different durations

By Allen Zhao for MotifDeck. Prepared with AI assistance.

A loop does not have to give every frame the same hold. If a three-frame animation holds for 100 ms, 200 ms and 100 ms, simply multiplying time by a fixed frames-per-second value will not reproduce that timing. Here is a small, engine-independent way to find the frame at a given elapsed time.

def frame_at(elapsed_ms, durations_ms):
    if elapsed_ms < 0 or not durations_ms or any(d <= 0 for d in durations_ms):
        raise ValueError('Use nonnegative elapsed time and positive durations')

    position = elapsed_ms % sum(durations_ms)
    for index, duration in enumerate(durations_ms):
        if position < duration:
            return index
        position -= duration

print([frame_at(t, [100, 200, 100]) for t in
       [0, 99, 100, 299, 300, 399, 400, 800]])
# [0, 0, 1, 1, 2, 2, 0, 0]
Enter fullscreen mode Exit fullscreen mode

The half-open intervals are important: frame 0 covers [0, 100), frame 1 covers [100, 300), and frame 2 covers [300, 400). At 400 ms the loop returns to frame 0. The example assumes elapsed time and durations use the same units and that the loop begins at zero.

This helper determines the frame to display; it does not emit events crossed during a long update. If you need attack or footstep events, process the elapsed interval separately so skipped frames do not silently lose events. Cache total duration and consider cumulative-duration search for large sequences or many simultaneous characters.

MotifDeck is an AI game-art workspace I work on. Its animation workflow includes choosing frames and adjusting their timing after motion generation. This example is general animation logic; it is not a claim about a specific MotifDeck export implementation.

Top comments (0)