如何按各影格的不同停留時間找出動畫目前影格
Find the current animation frame when holds have different durations
這個與遊戲引擎無關的範例,以各影格的停留時間及已經過時間計算循環動畫目前應顯示的影格。三影格分別停留 100 ms、200 ms 和 100 ms,累計 400 ms 後回到第 0 格;長時間更新期間略過的影格事件則須另外處理。
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]
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.
來源:DEV Community · dev.to