How do I load an image into a sprite instead of drawing a shape for the sprite? Ex: I load a 50x50 image into a sprite instead of drawing a 50x50 rect
Here is my spr
First load the image in the global scope or in a separate module and import it. Don't load it in the __init__
method, otherwise it has to be read from the hard disk every time you create an instance and that's slow.
Now you can assign the global IMAGE
in the class (self.image = IMAGE
) and all instances will reference this image.
import pygame as pg
pg.init()
# The screen/display has to be initialized before you can load an image.
screen = pg.display.set_mode((640, 480))
IMAGE = pg.image.load('an_image.png').convert_alpha()
class Player(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = IMAGE
self.rect = self.image.get_rect(center=pos)
If you want to use different images for the same class, you can pass them during the instantiation:
class Player(pg.sprite.Sprite):
def __init__(self, pos, image):
super().__init__()
self.image = image
self.rect = self.image.get_rect(center=pos)
player1 = Player((100, 300), IMAGE1)
player2 = Player((300, 300), IMAGE2)
Use the convert or convert_alpha
(for images with transparency) methods to improve the blit performance.
If the image is in a subdirectory (for example "images"), construct the path with os.path.join:
import os.path
import pygame as pg
IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()