You can create animations with the displayio library using sprite sheets. Sprite sheets can be thought of as an array of images. They can be iterated through just like an array of variables, strings or integers in code.
If the sprite sheet is set up with images that are sequential, then it will appear as an animation when they're played. You can do this by splitting out of the layers of a .GIF or creating your own artwork.
To begin animating your sprites, you'll setup your matrix and display objects as usual with the displayio and adafruit_matrixportal libraries.
The bitmap sprite sheet is brought into the code with the adafruit_imageload library. This bitmap is sliced into a TileGrid
, which will be how the images will be iterated through to create an animation.
matrix = Matrix(width=32, height=32) display = matrix.display group = displayio.Group() parrot_bit, parrot_pal = adafruit_imageload.load("/partyParrotsTweet.bmp", bitmap=displayio.Bitmap, palette=displayio.Palette) parrot_grid = displayio.TileGrid(parrot_bit, pixel_shader=parrot_pal, width=1, height=1, tile_height=32, tile_width=32, default_tile=10, x=0, y=0) group.append(parrot_grid) display.root_group = group
Two variables are needed to animate a sprite: one to track the index of the TileGrid
and one to track the time. p
will be used as the TileGrid
index and party
will be used to track time with time.monotonic()
.
In the loop, every 0.1
seconds, the TileGrid
's index advances by 1
. You can increase or decrease the timing to adjust the speed for your animation.
When p
reaches the end of the TileGrid
array, it is reset to 0
so that the animation can loop.
party = 0 p = 0 while True: if (party + 0.1) < time.monotonic(): parrot_grid[0] = p p += 1 party = time.monotonic() if p > 9: p = 0
And that's it! With just a few lines of code, you can get a looping animation running (or partying) on your matrix display.
Page last edited March 08, 2024
Text editor powered by tinymce.