我正在尝试编写一个简单的pygame程序,其中一些框在屏幕上移动。我正在关注this example。
本教程具有以下结构:
class Box(pygame.sprite.Sprite):
...
def update(self, currtime):
if self.next_update_time < current_time:
print time.time() # I added this to debug
# Do some stuff
self.next_update_time = current_time + 10
box = Box()
while True:
pygame.time.delay(10)
time = pygame.time.get_ticks()
box.update(time)
我的箱子移动了,但不是很顺利。它们加速并减慢了一点点。当我绘制更新发生的点时,我得到this。
这看起来像我正在遵循的教程中提出的设计有问题吗?这是我硬件的问题吗?
编辑: 根据Radomir Dopieralski的回答,更好的方法是:
class Box(pygame.sprite.Sprite):
...
def update(self):
# Do some stuff
box = Box()
clock = pygame.time.Clock()
while True:
clock.tick(100)
box.update()
答案 0 :(得分:2)
问题是pygame.time.delay(10)
将始终等待同一时间,无论你在游戏循环中绘制的盒子和其他东西花了多长时间。所以等待的总时间是10+render_time
。
幸运的是,PyGame提供了一个解决方案:pygame.time.Clock
类和它的.tick(framerate)
方法,它记住上次使用的时间,并根据它等待更短或更长的时间,以保持帧速率不变。
答案 1 :(得分:1)
我认为你需要使用pygame.time提供的时钟对象:
c = pygame.time.Clock()
while True:
dt = c.tick(framerate) # 0 for framerate removes the cap
...
ex_box.update(dt)
,更新方法如下所示:
def update(self, miliseconds_passed):
self.pos[0] += self.spped[0] * dt # Speed must be in pixels_per_millisecond
self.pos[1] += self.spped[1] * dt
注意:
如果您希望速度以每秒像素为单位,则必须执行“* dt / 1000”。只是“* dt”的内容。
如果你想以m / s的速度制作速度,如果必须设置一个常数'每米像素'并将速度乘以dt / 1000。 * ppm