Python 动画时序

4 投票
3 回答
5585 浏览
提问于 2025-04-15 21:44

我现在正在用Python制作一个精灵图工具,这个工具可以把组织好的内容导出成一个xml文档。不过在尝试制作动画预览的时候,我遇到了一些问题。我不太确定怎么用Python来控制帧率。比如说,假设我已经有了所有需要的帧数据和绘图函数,我该怎么编写代码来让它以每秒30帧(或者其他任意的速度)来显示呢?

3 个回答

0

你可以试试使用select这个东西吗?它通常用来等待输入输出操作完成,不过看看它的用法:

select.select(rlist, wlist, xlist[, timeout])

所以,你可以这样做:

timeout = 30.0
while true:
    if select.select([], [], [], timeout):
        #timout reached
        # maybe you should recalculate your timeout ?        
1

threading 模块里,有一个叫 Timer 的类。对于某些情况来说,使用它可能比用 time.sleep 更方便。

>>> from threading import Timer
>>> def hello(who):
...    print 'hello %s' % who
... 
>>> t = Timer(5.0, hello, args=('world',))
>>> t.start()      # and five seconds later...
hello world
8

最简单的方法是使用 Pygame

import pygame
pygame.init()

clock = pygame.time.Clock()
# or whatever loop you're using for the animation
while True:
    # draw animation
    # pause so that the animation runs at 30 fps
    clock.tick(30)

第二简单的方法是手动操作:

import time

FPS = 30
last_time = time.time()
# whatever the loop is...
while True:
    # draw animation
    # pause so that the animation runs at 30 fps
    new_time = time.time()
    # see how many milliseconds we have to sleep for
    # then divide by 1000.0 since time.sleep() uses seconds
    sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0
    if sleep_time > 0:
        time.sleep(sleep_time)
    last_time = new_time

撰写回答