简体   繁体   中英

Pyglet raising an error when trying to draw certain sprites/batches

I am creating a game in pyglet and I am running into this error:

pyglet.gl.lib.GLException: (0x502): Invalid operation. The specified operation is not allowed in the current state.

It is raised when I try this particular part of my code:

@window.event
def on_draw():
    window.clear()

    current = SHIP[player.getroomnum()] # Get current room 
    current.bg.blit(0, 0) # Weirdly blitting the background image does NOT raise an error
    
    # Error is raised here every .draw() call

    current.cut_batch.draw() # Batch of sprites

    player.hp_batch.draw() # Batch of pyglet.shapes
    minimapbg.draw()

    current.minibatch.draw()
    current.mini_tracker.draw()

    controls.batch.draw()

It is also worth noting that if I create a random pyglet sprite or shape and try and draw that in this code block I do not get any errors. So it could be an issue with the creation of the sprite, however I can't see how that would be the case:

# Creating a sprite in the sprite batch cut_batch: 

pyglet.sprite.Sprite(
    pyglet.image.load(f"{cwd}/Assets/cut_{door.lower()}door.png"),
    x=0,
    y=0,
    batch=self.cut_batch,
) 

This object is added to a list holding all the sprites needed for the whole batch in order to avoid giving variable names to every object in the batch (there are around 4 usually). I use a similar technique for the shape batch, there is a list of rectangles held in a class each with the hp_batch set as their batch.

I tried running my code and encountered the error mentioned before, I can't seem to find what causes the error online. I checked the types of the objects in the batches and they are all either pyglet.shapes.Rectangle or pyglet.sprite.Sprite as expected. The error is explicitly when I try and draw the object or batch.

Your problem could be that you are creating the drawable objects before the creation of the window. I don't fully understand why this happens, though

A very minimal example:

import pyglet

sprite = pyglet.sprite.Sprite(pyglet.image.load("image.png"))
window = pyglet.window.Window(800,600, "Title")    

@window.event
def on_draw():
    sprite.draw()

pyglet.app.run()

will give you the same error. If you swap the second and third line:

import pyglet

window = pyglet.window.Window(800,600, "Title")   # CREATE WINDOW FIRST!
sprite = pyglet.sprite.Sprite(pyglet.image.load("image.png"))

@window.event
def on_draw():
    sprite.draw()

pyglet.app.run()

will run ok. Surprisingly, as you said, if you add another sprite in the first example (after window creation), it runs ok as well (no need to actually draw this second sprite).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM