1

Pixel-perfect collisions from multi-sprite image

I want to do pixel-perfect collision checks. I have a sprite with 6 frames in PNG format with a transparent background, but they're all on a single spritesheet. (The 'enemy' sprites have 2 frames each.) I can animate them and move them fine.

How can I make a pygame surface object from only part of a loaded image? I suppose I could load each sprite frame individually, but this is laborious and doesn't seem like good coding.

More Info

I can turn the whole spritesheet into a mask easy enough as follows (originally in a spritesheet class but simplified here):

# Load image
sheet = pygame.image.load("spritesheet.png")
# Create mask
sheet_mask = pygame.mask.from_surface(sheet)

I could simply use the rect of the current frame to detect collisions, but this will be very unsatisfying because collisions would seem to happen without contact sometimes. An pygame has this wonderful mask object for this sort of thing.

In each loop of the main game loop I want to check the appropriate frame of one sprite against the appropriate frame of the other. I have been trying to create a mask for each frame then store them in a list.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
manute
  • 11
  • 2

1 Answers1

0

Use the subsurface() method to get a rectangular subsurface from a pygame.Surface:

sheet = pygame.image.load("spritesheet.png")

rect_area = pygame.Rect(left, top, width, heigth)
sprite_from_sheet = sheet.subsurface(rect_area)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174