Pyglet - 游戏运行缓慢,对事件和东西感到困惑

Syk*_*lis 3 python events pyglet python-3.x

好的,我正在用 Pyglet 制作一个小游戏/原型,我对事件感到困惑。游戏运行不佳,通过分析我知道这是因为on_draw()每秒被调用 60 次,因为pyglet.clock.schedule_interval(). 我不完全知道为什么on_draw()目前正在使用它可以使用的所有 CPU,如果知道的话会很高兴。通过更多的分析,我知道绘制 100 个 Sprite 也需要大量的 CPU,比我认为它应该占用的要多(我什至不知道它应该占用 CPU 还是只占用 GPU)。

  1. on_draw()默认情况下会做什么,我可以避免任何无用的额外内容吗?
  2. 我怎样才能schedule_interval()不触发on_draw()
  3. 任何有效的绘图/位图方法?

一些代码:

screen = pyglet.window.Window(800, 600, vsync=False, caption="Project")

tileimage = pyglet.image.create(50, 50, pyglet.image.SolidColorImagePattern((0, 255, 0, 255)))

class tileclass(pyglet.sprite.Sprite):
    def __init__(self, x, y):
        pyglet.sprite.Sprite.__init__(self, tileimage)
        self.x = x
        self.y = y
        self.rect = pygame.Rect(self.x - self.width / 2, self.y - self.height / 2, self.width, self.height)
        self.image.anchor_x = self.width // 2
        self.image.anchor_y = self.height // 2

tiles = []

x = 25
y = 25
for i in range(100):
    tiles.append(tileclass(x, y))
    if x == 475:
        x = 25
        y+=50
    else:
        x+=50

@screen.event
def on_draw():
    screen.clear()
    for t in tiles:
        t.draw()
    fps.draw()

pyglet.clock.schedule_interval(update, 1/60) #Logic stuff
Run Code Online (Sandbox Code Playgroud)

谢谢。

vib*_*blo 5

尝试将您的精灵添加到批处理中并绘制它。在 pyglet 中,由于 OpenGL 的工作原理,它进行绘制调用的速度很慢。基本上你想尽量减少你做的抽奖次数,并尽可能多地把东西放在一起。通过创建批处理,然后向其中添加所有精灵,最后仅绘制批处理,我在您的示例中获得了巨大改进。

http://pyglet.org/doc/programming_guide/displaying_images.html#sprites

这与 pygame 形成了一点对比,在 pygame 中,小图像比大图像便宜,并且您通常通过绘制更少的像素来使游戏更快(通常只重绘自上一帧以来发生变化的屏幕部分等)。