Note: I do not want to use pygame sprites.
I am making a simple game and I need a way to detect if two images overlap using pixel-perfect collision in pygame. All the answers I have found so far require that I use pygame sprites, which I prefer not to use because I have less control over the objects.
(These images have transparent backgrounds)
First of all, don't be afraid of Sprites.
A
Spriteis just a simple class with an image (aSurfacethat is stored in theimageattribute) and the size and position of the image (aRectstored in the rect attribute).So when you use a class like this:
you could simple use the
Spriteclass instead, since not much would change:Instead, it becames simpler, because we can let pygame handle blitting the image to the screen.
So, to use pixel perfect collision, you can use pygame's
Maskclass. Usepygame.mask.from_surfaceto create aMaskfrom yourSurface, and usepygame.mask.Mask.overlapto check if two masks overlap.It's easier to use when you use the Sprite class, since you could just use functions like
spritecollidetogether withcollide_mask.But if you don't want to use the
Spriteclass, just take a look howcollide_maskis implemented to see how you can use masks: