Python Pyglet:火球射手,每当我按下一个指定的键,火球就会不断加速,而不是保持恒定的速度
您如何使此代码工作?只需安装Python Pyglet:火球射手,每当我按下一个指定的键,火球就会不断加速,而不是保持恒定的速度,python,pyglet,Python,Pyglet,您如何使此代码工作?只需安装pyglet,并将“fireball.png”更改为存储在将此代码保存到文件的目录中的图像名称 import pyglet class Fireball(pyglet.sprite.Sprite): def __init__(self, batch): pyglet.sprite.Sprite.__init__(self, pyglet.resource.image("fireball.png")) # replace "fi
pyglet
,并将“fireball.png”
更改为存储在将此代码保存到文件的目录中的图像名称
import pyglet
class Fireball(pyglet.sprite.Sprite):
def __init__(self, batch):
pyglet.sprite.Sprite.__init__(self, pyglet.resource.image("fireball.png"))
# replace "fireball.png" with your own image stored in dir of fireball.py
self.x = 10 # Initial x coordinate of the fireball
self.y = 10 # Initial y coordinate of the fireball
class Game(pyglet.window.Window):
def __init__(self):
pyglet.window.Window.__init__(self, width = 315, height = 220)
self.batch_draw = pyglet.graphics.Batch()
self.fps_display = pyglet.clock.ClockDisplay()
self.fireball = []
def on_draw(self):
self.clear()
self.fps_display.draw()
self.batch_draw.draw()
if len(self.fireball) != 0: # Allow drawing of multiple
for i in range(len(self.fireball)): # fireballs on screen
self.fireball[i].draw() # at the same time
def on_key_press(self, symbol, modifiers):
if symbol == pyglet.window.key.A:
self.fireball.append(Fireball(batch = self.batch_draw))
pyglet.clock.schedule_interval(func = self.update, interval = 1/60.)
print "The 'A' key was pressed"
def update(self, interval):
for i in range(len(self.fireball)):
self.fireball[i].x += 1 # why do fireballs get faster and faster?
if __name__ == "__main__":
window = Game()
pyglet.app.run()
该代码创建了一个黑色背景屏幕,在该屏幕上显示fps,每当您按下a
键时,就会从位置(10,10)沿x方向射出一个火球
你会注意到你射出的火球越多,所有火球开始移动的速度就越快
问题:
火球的速度越来越快,因为每次按A键时,都会向调度程序添加另一个调用
self.update
。因此,每次调用self.update
的次数越来越多,导致位置更新的次数越来越多。要修复此问题,请将下面的行移动到\uuuu init\uuuu()
pyglet.clock.schedule_interval(func = self.update, interval = 1/60.)