【发布时间】:2010-04-18 02:49:33
【问题描述】:
我目前正在使用 python 中的 sprite sheet 工具将组织导出到 xml 文档中,但我在尝试为预览设置动画时遇到了一些问题。我不太确定如何用 python 计时帧速率。例如,假设我拥有所有适当的帧数据和绘图函数,我将如何编写时序以每秒 30 帧(或任何其他任意速率)显示它。
【问题讨论】:
标签: python animation sprite timing
我目前正在使用 python 中的 sprite sheet 工具将组织导出到 xml 文档中,但我在尝试为预览设置动画时遇到了一些问题。我不太确定如何用 python 计时帧速率。例如,假设我拥有所有适当的帧数据和绘图函数,我将如何编写时序以每秒 30 帧(或任何其他任意速率)显示它。
【问题讨论】:
标签: python animation sprite timing
最简单的方法是使用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
【讨论】:
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
【讨论】:
你可以使用 select 吗?它通常用于等待 I/O 完成,但请看一下签名:
select.select(rlist, wlist, xlist[, timeout])
所以,你可以这样做:
timeout = 30.0
while true:
if select.select([], [], [], timeout):
#timout reached
# maybe you should recalculate your timeout ?
【讨论】: