File: sprite_batching.py

package info (click to toggle)
pyglet 2.0.17%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 15,560 kB
  • sloc: python: 80,579; xml: 50,988; ansic: 171; makefile: 146
file content (50 lines) | stat: -rw-r--r-- 1,496 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import random

import pyglet

window = pyglet.window.Window(vsync=False)

# Set example resource path.
pyglet.resource.path = ['../resources']
pyglet.resource.reindex()

# Load example image from resource path.
# Avoid using pyglet.image.load as it creates multiple textures.
# Resource will load images into a texture atlas, allowing significantly faster performance.
image = pyglet.resource.image("pyglet.png")

# Anchor point on an image is bottom left corner by default.
# Set to center point with anchor properties.
image.anchor_x = image.width // 2
image.anchor_y = image.height // 2

# Batching allows rendering groups of objects all at once instead of drawing one by one.
batch = pyglet.graphics.Batch()

scales = [1.0, 0.75, 0.5, 0.25]

sprites = []
# Create 1000 sprites at various scales.
for i in range(1000):
    sprite = pyglet.sprite.Sprite(image,
                                  x=random.randint(0, window.width),
                                  y=random.randint(0, window.height),
                                  batch=batch)  # specify the batch to enter the sprites in.

    # Randomize scale.
    sprite.scale = random.choice(scales)

    # Random color multiplier.
    sprite.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

    # Add sprites to keep in memory, like a list. Otherwise they will get GC'd when out of scope.
    sprites.append(sprite)


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


pyglet.app.run()