I searched around but found nothing helpfull.
I have in pygame an png image as a player, with a transparant background. I want to create a mask of only the player not the background. I can do this but I get a rectangle as a mask, instead of the player's shape.
how can I solve this?
here is my code:
import pygame
import os
pygame.init()
# Create display
screen_width=1600
screen_height=960
screen = pygame.display.set_mode((screen_width, screen_height),pygame.NOFRAME)
# Set framerate
clock = pygame.time.Clock()
fps = 60
#load images
player_img=pygame.image.load('img/player/Idle/1.png').convert_alpha()
player_mask=pygame.mask.from_surface(player_img)
player_maskSurf=pygame.Surface((player_img.get_width(),player_img.get_height()),masks=player_mask)
#define colors
BG=(124,64,204)
red = (255,0,0)
blue = (0,0,255)
run = True
while run:
clock.tick(fps)
screen.fill(BG)
screen.blit(player_img, (800-player_img.get_width()/2,480-player_img.get_height()/2))
screen.blit(player_maskSurf, (800-player_img.get_width()/2,480-player_img.get_height()/2))
for event in pygame.event.get():
#quit game
if event.type == pygame.QUIT:
run = False
#keyboard presses
if event.type==pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
pygame.display.update()
pygame.quit()
Thank you
The mask argument of a Surface is not considered to be a pygame.Mask
object. See pygame.Surface
:
[...] The masks are a set of 4 integers representing which bits in a pixel will represent each color. Normal Surfaces should not require the masks argument.
Use pygame.mask.Mask.to_surface
to convert a pygame.Mask
to a pygame.Surface
:
player_maskSurf=pygame.Surface((player_img.get_width(),player_img.get_height()),masks=player_mask)
player_maskSurf = player_mask.to_surface()
player_maskSurf.set_colorkey((0, 0, 0)) # this is optional