How to blit from the x and y coordinates of an image in Pygame?

Question:

I’m trying to lessen the number of files I need for my pygame project by instead of having a folder with for example 8 boots files, I can make 1 bigger image that has all of them 8 pictures put next to each other and depending on animation tick, that specific part of the image gets blitted.

Currently, I utilise lists.

right = ["playerdesigns/playerright0.png","playerdesigns/playerright1.png","playerdesigns/playerright2.png","playerdesigns/playerright3.png"]

my code then just depending on animation tick, takes on of those files and blits it

but I wish to make it into one playerright.png image file that 0-100 Xpixels of the picture has playerright1.png, 101-200 Xpixels has playerright2.png etc, and then depending on need, I can blit 100 wide image from any point.

Asked By: Kuiu

||

Answers:

You can define a subsurface that is directly linked to the source surface with the method subsurface:

subsurface(Rect) -> Surface

Returns a new Surface that shares its pixels with its new parent. The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other.

The Rect argument of subsurface specifies the rectangular area for the sub-image. It can either be a pygame.Rect object or a tuple with 4 components (x, y, width, height).

For example, if you have an image that contains 3 100×100 size sub-images:

right_surf = pygame.image.load("playerdesigns/playerright.png")
right_surf_list = [right_surf.subsurface((i*100, 0, 100, 100)) for i in range(3)]
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.