Named shapes in pyglet

Viewed 229

Why do shapes and other objects in pyglet have to be named (as in assigned variables) ? The Rectangle below named "test" renders successfully, the one a line below does not. Why is that?

from pyglet import shapes

WHITE = (255, 255, 255)

HEIGHT = 1080
WIDTH = 720


window = pyglet.window.Window(HEIGHT, WIDTH)
background = pyglet.graphics.Batch()


test = shapes.Rectangle(200, 200, 50, 50, color=WHITE, batch=background) # Renders successfuly
shapes.Rectangle(300, 300, 50, 50, color=WHITE, batch=background)        # Does not render


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


pyglet.app.run()
1 Answers

Here you are using pyglet.graphics.Batch() to render the shape objects together i.e. test(the first rectangle) + the second rectangle. A batch manages a set of objects that will be drawn at once, and hence to instantiate the objects that need to be drawn, they need to have a reference against which they can be mapped to that batch.

To draw a rectangle as is, without assigning it to a varible can be done by using the pyglet.graphics.draw() function directly by passing in the primitive type, rectanggle coordinates and formatstring.

Related