Search code examples
pythoneventspython-3.xpyglet

Pyglet - Game running slow, confused about events and stuff


Okay, I'm making a little game/prototype with Pyglet, and I'm getting confused about events. The game runs poorly, and by profiling I know it's because of on_draw() getting called 60 times per second because of pyglet.clock.schedule_interval(). I don't exactly know why on_draw() is currently using all the CPU it can get its hands on, and that would be nice to know. By profiling some more, I know that drawing 100 Sprites takes a lot of CPU too, more than I think it should be taking (I don't even know if it should be taking CPU or only GPU).

  1. What does on_draw() do by default and can I avoid any useless extra stuff?
  2. How can I make so that schedule_interval() doesn't trigger on_draw()?
  3. Any effective drawing/blitting methods?

Some code:

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

Thanks.


Solution

  • Try and add your sprites to a batch and draw that instead. In pyglet its slow to do draw calls as thats how OpenGL works. Basically you want to minimize the number of draws you do and batch things together as much as possible. I got a massive improvement in your example by creating a batch and then adding all the sprites to it and finally only draw the batch.

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

    This is a bit of contrast to pygame where a small image is cheaper than a large one and you usually make your game faster by drawing less pixels (typically only redraw parts of screen that has changes since last frame and so on).