Drawing polygons onto a sprite's surface as it's image in pygame

Viewed 845

I want to run collision detection on non-rectangular shapes. (not shapes loaded from an image) the shapes are polygons. I want to draw the polygons on to their own surfaces so that I can generate a collision mask from that, which i will then use to check collisions with the player. Right now my code should be drawing polygon shapes onto each of the block's surfaces, ready to be turned into a collision mask. but for some reason it doesnt seem to be doing that right. heres my code:

import pygame
import random

screen = pygame.display.set_mode((800,800))
pygame.init()
sprite_list = pygame.sprite.Group()


class Block(pygame.sprite.Sprite):
    def __init__(self, size, pos):
        pygame.sprite.Sprite.__init__(self)
        self.size = size
        self.image = pygame.Surface([size[0], size[1]])
        self.rect = self.image.get_rect()
        self.rect[0] = pos[0]
        self.rect[1] = pos[1]

    def update(self):
        pygame.draw.polygon(self.image, [100,100,30], [((self.rect[0]+ self.size[0]/2),self.rect[1]), (self.rect[0], self.rect[1] + self.size[1]), (self.rect[0]+ self.size[0], self.rect[1] + self.size[1])])

for i in range(5):
    cube = Block((20,20), (random.randint(0,800),random.randint(0,800)))
    sprite_list.add(cube)

run = True

while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    screen.fill((255,255,255))

    sprite_list.update()

    sprite_list.draw(screen)
    pygame.display.update()
1 Answers

You're pretty much there already.

In your sprite, define the Surface (with a transparent background) for Block.image, draw the polygon into that surface, and then create a mask from that. If you don't use a transparent background, you need to have a > 127 difference in colour-threshold (or pass it as a parameter to mask.from_surface() ).

class Block(pygame.sprite.Sprite):
    def __init__(self, size, pos):
        pygame.sprite.Sprite.__init__(self)

        # create transparent background image
        self.image = pygame.Surface( size, pygame.SRCALPHA, 32 )  
        self.rect = self.image.get_rect()
        self.rect.topleft = pos

        # Draw a random polygon into the image
        points = getRandomPolygonPointList( random.randrange( 3, 12 ), size )
        pygame.draw.polygon( self.image, WHITE, points )

        # Create the collision mask (anything not transparent)
        self.mask = pygame.mask.from_surface( self.image )  

   def update( self ):
       pass  # TODO  
Related