Sprite Lists
- class arcade.SpriteList(use_spatial_hash: bool = False, spatial_hash_cell_size: int = 128, atlas: TextureAtlasBase | None = None, capacity: int = 100, lazy: bool = False, visible: bool = True)[source]
Bases:
Generic
[SpriteType
]The purpose of the spriteList is to batch draw a list of sprites. Drawing single sprites will not get you anywhere performance wise as the number of sprites in your project increases. The spritelist contains many low level optimizations taking advantage of your graphics processor. To put things into perspective, a spritelist can contain tens of thousands of sprites without any issues. Sprites outside the viewport/window will not be rendered.
If the spritelist are going to be used for collision it’s a good idea to enable spatial hashing. Especially if no sprites are moving. This will make collision checking a lot faster. In technical terms collision checking is
O(1)
with spatial hashing enabled andO(N)
without. However, if you have a list of moving sprites the cost of updating the spatial hash when they are moved can be greater than what you save with spatial collision checks. This needs to be profiled on a case by case basis.For the advanced options check the advanced section in the Arcade documentation.
- Parameters:
use_spatial_hash – If set to True, this will make creating a sprite, and moving a sprite in the SpriteList slower, but it will speed up collision detection with items in the SpriteList. Great for doing collision detection with static walls/platforms in large maps.
spatial_hash_cell_size – The cell size of the spatial hash (default: 128)
atlas – (Advanced) The texture atlas for this sprite list. If no atlas is supplied the global/default one will be used.
capacity – (Advanced) The initial capacity of the internal buffer. It’s a suggestion for the maximum amount of sprites this list can hold. Can normally be left with default value.
lazy – (Advanced)
True
delays creating OpenGL resources for the sprite list until either itsdraw()
orinitialize()
method is called. See Lazy SpriteLists to learn more.visible – Setting this to False will cause the SpriteList to not be drawn. When draw is called, the method will just return without drawing.
- DEFAULT_TEXTURE_FILTER: ClassVar[tuple[int, int]] = (9729, 9729)
The default texture filter used when no other filter is specified. This can be used to change the global default for all spritelists
Example:
from arcade import gl # Set global default to nearest filtering (pixelated) arcade.SpriteList.DEFAULT_TEXTURE_FILTER = gl.NEAREST, gl.NEAREST # Set global default to linear filtering (smooth). This is the default. arcade.SpriteList.DEFAULT_TEXTURE_FILTER = gl.NEAREST, gl.NEAREST
- property alpha: int
Get or set the alpha/transparency of the entire spritelist.
This is a byte value from 0 to 255 were 0 is completely transparent/invisible and 255 is opaque.
- property alpha_normalized: float
Get or set the alpha/transparency of all the sprites in the list.
This is a floating point number from 0.0 to 1.0 were 0.0 is completely transparent/invisible and 1.0 is opaque.
This is a shortcut for setting the alpha value in the spritelist color.
- append(sprite: SpriteType) None [source]
Add a new sprite to the list.
- Parameters:
sprite – Sprite to add to the list.
- property atlas: TextureAtlasBase | None
Get the texture atlas for this sprite list
- property buffer_angles: Buffer
Get the internal OpenGL angle buffer for the spritelist.
This buffer contains a series of 32 bit floats representing the rotation angle for each sprite in degrees.
This buffer is attached to the
geometry
instance with namein_angle
.
- property buffer_colors: Buffer
Get the internal OpenGL color buffer for this spritelist.
This buffer contains a series of 32 bit floats representing the RGBA color for each sprite. 4 x floats = RGBA.
This buffer is attached to the
geometry
instance with namein_color
.
- property buffer_indices: Buffer
Get the internal index buffer for this spritelist.
The data in the other buffers are not in the correct order matching
spritelist[i]
. The index buffer has to be used used to resolve the right order. It simply contains a series of integers referencing locations in the other buffers.Also note that the length of this buffer might be bigger than the number of sprites. Rely on
len(spritelist)
for the correct length.This index buffer is attached to the
geometry
instance and will be automatically be applied the the input buffers when rendering or transforming.
- property buffer_positions: Buffer
Get the internal OpenGL position buffer for this spritelist.
The buffer contains 32 bit float values with x, y and z positions. These are the center positions for each sprite.
This buffer is attached to the
geometry
instance with namein_pos
.
- property buffer_sizes: Buffer
Get the internal OpenGL size buffer for this spritelist.
The buffer contains 32 bit float width and height values.
This buffer is attached to the
geometry
instance with namein_size
.
- property buffer_textures: Buffer
Get the internal openGL texture id buffer for the spritelist.
This buffer contains a series of single 32 bit floats referencing a texture ID. This ID references a texture in the texture atlas assigned to this spritelist. The ID is used to look up texture coordinates in a 32bit floating point texture the texture atlas provides. This system makes sure we can resize and rebuild a texture atlas without having to rebuild every single spritelist.
This buffer is attached to the
geometry
instance with namein_texture
.Note that it should ideally an unsigned integer, but due to compatibility we store them as 32 bit floats. We cast them to integers in the shader.
- clear(deep: bool = True) None [source]
Remove all the sprites resetting the spritelist to it’s initial state.
The complexity of this method is
O(N)
with a deep clear (default).If ALL the sprites in the list gets garbage collected with the list itself you can do an
O(1)`
clear usingdeep=False
. Make sure you know exactly what you are doing before using this option. Any lingering sprite reference will cause a massive memory leak. Thedeep
option will iterate all the sprites and remove their references to this spritelist. Sprite and SpriteList have a circular reference for performance reasons.- Parameters:
deep – Wether to do a deep clear or not. Default is
True
.
- property color: Color
Get or set the multiply color for all sprites in the list RGBA integers
This will affect all sprites in the list, and each value must be between 0 and 255.
The color may be specified as any of the following:
an RGBA
tuple
with each channel value between 0 and 255an instance of
Color
an RGB
tuple
, in which case the color will be treated as opaque
Each individual sprite can also be assigned a color via its
color
property.When
SpriteList.draw()
is called, each pixel will default to a value equivalent to the following:Convert the sampled texture, sprite, and list colors into normalized floats (0.0 to 1.0)
Multiply the color channels together:
texture_color * sprite_color * spritelist_color
Multiply the floating point values by 255 and round the result
- property color_normalized: tuple[float, float, float, float]
Get or set the spritelist color in normalized form (0.0 -> 1.0 floats).
This property works the same as
color
.
- draw(*, filter: int | tuple[int, int] | None = None, pixelated: bool | None = None, blend_function: tuple[int, int] | tuple[int, int, int, int] | None = None) None [source]
Draw this list of sprites.
Uninitialized sprite lists will first create OpenGL resources before drawing. This may cause a performance stutter when the following are true:
You created the sprite list with
lazy=True
You did not call
initialize()
before drawingYou are initializing many sprites and/or lists at once
See Lazy SpriteLists to learn more.
- Parameters:
filter – Optional parameter to set OpenGL filter, such as gl.GL_NEAREST to avoid smoothing.
pixelated –
True
for pixelated andFalse
for smooth interpolation. Shortcut for setting filter to GL_NEAREST for a pixelated look. The filter parameter have precedence over this.blend_function – Optional parameter to set the OpenGL blend function used for drawing the sprite list, such as ‘arcade.Window.ctx.BLEND_ADDITIVE’ or ‘arcade.Window.ctx.BLEND_DEFAULT’
- draw_hit_boxes(color: tuple[int, int, int, int] = (0, 0, 0, 255), line_thickness: float = 1.0) None [source]
Draw all the hit boxes in this list.
Warning
This method is slow and should only be used for debugging.
- Parameters:
color – The color of the hit boxes
line_thickness – The thickness of the lines
- enable_spatial_hashing(spatial_hash_cell_size: int = 128) None [source]
Turn on spatial hashing unless it is already enabled with the same cell size.
- Parameters:
spatial_hash_cell_size – The size of the cell in the spatial hash.
- extend(sprites: Iterable[SpriteType] | SpriteList[SpriteType]) None [source]
Extends the current list with the given iterable
- Parameters:
sprites – Iterable of Sprites to add to the list
- property geometry: Geometry
Returns the internal OpenGL geometry for this spritelist. This can be used to execute custom shaders with the spritelist data.
One or multiple of the following inputs must be defined in your vertex shader:
in vec2 in_pos; in float in_angle; in vec2 in_size; in float in_texture; in vec4 in_color;
- index(sprite: SpriteType) int [source]
Return the index of a sprite in the spritelist
- Parameters:
sprite – Sprite to find and return the index of
- initialize() None [source]
Request immediate creation of OpenGL resources for this list.
Calling this method is optional. It only has an effect for lists created with
lazy=True
. If this method is not called, uninitialized sprite lists will automatically initialize OpenGL resources on their firstdraw()
call instead.This method is useful for performance optimization, advanced techniques, and writing tests. Do not call it across thread boundaries. See Lazy SpriteLists to learn more.
- insert(index: int, sprite: SpriteType) None [source]
Inserts a sprite at a given index.
- Parameters:
index – The index at which to insert
sprite – The sprite to insert
- move(change_x: float, change_y: float) None [source]
Moves all Sprites in the list by the same amount. This can be a very expensive operation depending on the size of the sprite list.
- Parameters:
change_x – Amount to change all x values by
change_y – Amount to change all y values by
- pop(index: int = -1) SpriteType [source]
Attempt to pop a sprite from the list.
This works like popping from a standard Python
list
:If the list is empty, raise an
IndexError
If no
index
is passed, try to pop the lastSprite
in the list
- Parameters:
index – Index of sprite to remove (defaults to
-1
for the last item)
- preload_textures(texture_list: Iterable['Texture']) None [source]
Preload a set of textures that will be used for sprites in this sprite list.
- Parameters:
texture_list – List of textures.
- remove(sprite: SpriteType) None [source]
Remove a specific sprite from the list.
- Parameters:
sprite – Item to remove from the list
- rescale(factor: float) None [source]
Rescale all sprites in the list relative to the spritelists center.
- sort(*, key: Callable, reverse: bool = False) None [source]
Sort the spritelist in place using
<
comparison between sprites. This function is similar to python’slist.sort()
.Example sorting sprites based on y-axis position using a lambda:
# Normal order spritelist.sort(key=lambda x: x.position[1]) # Reversed order spritelist.sort(key=lambda x: x.position[1], reverse=True)
Example sorting sprites using a function:
# More complex sorting logic can be applied, but let's just stick to y position def create_y_pos_comparison(sprite): return sprite.position[1] spritelist.sort(key=create_y_pos_comparison)
- Parameters:
key – A function taking a sprite as an argument returning a comparison key
reverse – If set to
True
the sprites will be sorted in reverse
- swap(index_1: int, index_2: int) None [source]
Swap two sprites by index.
- Parameters:
index_1 – Item index to swap
index_2 – Item index to swap
- update(delta_time: float = 0.016666666666666666, *args, **kwargs) None [source]
Call the update() method on each sprite in the list.
- Parameters:
delta_time – Time since last update in seconds
*args – Additional positional arguments
**kwargs – Additional keyword arguments
- update_animation(delta_time: float = 0.016666666666666666, *args, **kwargs) None [source]
Call the update_animation in every sprite in the sprite list.
- Parameters:
delta_time – Time since last update in seconds
*args – Additional positional arguments
**kwargs – Additional keyword arguments
- property visible: bool
Get or set the visible flag for this spritelist.
If visible is
False
thedraw()
has no effect.
- write_sprite_buffers_to_gpu() None [source]
Ensure buffers are resized and fresh sprite data is written into the internal sprite buffers.
This is automatically called in
SpriteList.draw()
, but there are instances when using custom shaders we need to force this to happen since we might have not calledSpriteList.draw()
since the spritelist was modified.If you have added, removed, moved or changed ANY sprite property this method will synchronize the data on the gpu side (buffer resizing and writing in new data).
- class arcade.SpatialHash(cell_size: int)[source]
Bases:
Generic
[SpriteType
]A data structure best for collision checks with non-moving sprites.
It subdivides space into a grid of squares, each with sides of length
cell_size
. Moving a sprite from one place to another is the same as removing and adding it. Although moving a few can be okay, it can quickly add up and slow down a game.- Parameters:
cell_size – The width and height of each square in the grid.
- add(sprite: SpriteType) None [source]
Add a sprite to the spatial hash.
- Parameters:
sprite – The sprite to add
- cell_size: int
How big each grid cell is on each side.
Warning
Do not change this after creation!
Since each cell is a square, they’re used as both the width and height.
- get_sprites_near_point(point: tuple[float | int, float | int] | Vec2 | tuple[float | int, float | int, float | int] | Vec3) set[SpriteType] [source]
Return sprites in the same bucket as the given point.
- Parameters:
point – The point to check
- get_sprites_near_rect(rect: Rect) set[SpriteType] [source]
Return sprites in the same buckets as the given rectangle.
- Parameters:
rect – The rectangle to check (left, right, bottom, top)
- get_sprites_near_sprite(sprite: BasicSprite) set[SpriteType] [source]
Get all the sprites that are in the same buckets as the given sprite.
- Parameters:
sprite – The sprite to check
- hash(point: tuple[int, int]) tuple[int, int] [source]
Convert world coordinates to cell coordinates
- move(sprite: SpriteType) None [source]
Shortcut to remove and re-add a sprite.
- Parameters:
sprite – The sprite to move
- arcade.get_distance_between_sprites(sprite1: SpriteType, sprite2: SpriteType) float [source]
Returns the distance between the center of two given sprites
- Parameters:
sprite1 – Sprite one
sprite2 – Sprite two
- arcade.get_closest_sprite(sprite: SpriteType, sprite_list: SpriteList) Tuple[SpriteType, float] | None [source]
Given a Sprite and SpriteList, returns the closest sprite, and its distance.
- Parameters:
sprite – Target sprite
sprite_list – List to search for closest sprite.
- Returns:
A tuple containing the closest sprite and the minimum distance. If the spritelist is empty we return
None
.
- arcade.check_for_collision(sprite1: BasicSprite, sprite2: BasicSprite) bool [source]
Check for a collision between two sprites.
- Parameters:
sprite1 – First sprite
sprite2 – Second sprite
- Returns:
True
orFalse
depending if the sprites intersect.
- arcade.check_for_collision_with_list(sprite: SpriteType, sprite_list: SpriteList, method: int = 0) List[SpriteType] [source]
Check for a collision between a sprite, and a list of sprites.
- Parameters:
sprite – Sprite to check
sprite_list – SpriteList to check against
method –
Collision check method. Defaults to 0.
0: auto-select. (spatial if available, GPU if 1500+ sprites, else simple)
1: Spatial Hashing if available,
2: GPU based
3: Simple check-everything.
Note that while the GPU method is very fast when you cannot use spatial hashing, it’s also very slow if you are calling this function many times per frame. What method is the most appropriate depends entirely on your use case.
- Returns:
List of sprites colliding, or an empty list.
- arcade.check_for_collision_with_lists(sprite: BasicSprite, sprite_lists: Iterable[SpriteList[SpriteType]], method=1) List[SpriteType] [source]
Check for a collision between a Sprite, and a list of SpriteLists.
- Parameters:
sprite – Sprite to check
sprite_lists – SpriteLists to check against
method – Collision check method. 1 is Spatial Hashing if available, 2 is GPU based, 3 is slow CPU-bound check-everything. Defaults to 1.
- Returns:
List of sprites colliding, or an empty list.
- arcade.get_sprites_at_point(point: tuple[float | int, float | int] | Vec2 | tuple[float | int, float | int, float | int] | Vec3, sprite_list: SpriteList[SpriteType]) List[SpriteType] [source]
Get a list of sprites at a particular point. This function sees if any sprite overlaps the specified point. If a sprite has a different center_x/center_y but touches the point, this will return that sprite.
- Parameters:
point – Point to check
sprite_list – SpriteList to check against
- Returns:
List of sprites colliding, or an empty list.
- arcade.get_sprites_at_exact_point(point: tuple[float | int, float | int] | Vec2 | tuple[float | int, float | int, float | int] | Vec3, sprite_list: SpriteList[SpriteType]) List[SpriteType] [source]
Get a list of sprites whose center_x, center_y match the given point. This does NOT return sprites that overlap the point, the center has to be an exact match.
- Parameters:
point – Point to check
sprite_list – SpriteList to check against
- Returns:
List of sprites colliding, or an empty list.
- arcade.get_sprites_in_rect(rect: Rect, sprite_list: SpriteList[SpriteType]) List[SpriteType] [source]
Get a list of sprites in a particular rectangle. This function sees if any sprite overlaps the specified rectangle. If a sprite has a different center_x/center_y but touches the rectangle, this will return that sprite.
The rectangle is specified as a tuple of (left, right, bottom, top).
- Parameters:
rect – Rectangle to check
sprite_list – SpriteList to check against
- Returns:
List of sprites colliding, or an empty list.