[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
[pygame] Mask collision detection
Hi,
I´m having some trouble with detecting collisions between 2 masks.
What i´m trying to do is create a sort of a terrain with a polygon,
then drop a box that should keep dropping until it hits the "terrain".
With the following code I get 2 masks that when checked with
mask.count() are greater than 0.
Problem is they are not detecting each other. I tried both
pygame.mask.from_threshold and pygame.mask.from_surface to make a mask
of the polygon. For overlapping detection I tried Mask.overlap_area
and Mask.overlap. Both did not work.
Any help would be greatly appreciated
This is my code:
+-------------------------Main class:
import pygame
import Blok
from pygame.locals import *
def main():
pygame.init()
screen = pygame.display.set_mode((750, 500))
pygame.display.set_caption('Spike 2')
#Backgrounds
background2 = pygame.Surface(screen.get_size())
background2 = background2.convert()
background2.fill((0, 0, 250))
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0, 0, 250))
background.set_colorkey((0, 0, 250), RLEACCEL)
#Make the terrain polygon
area = [(0, 300), (290, 475), (450, 200), (550,475),(750,350),
(750,500),(0,500)]
colour = (250, 0, 0)
pygame.draw.polygon(background, colour, area)
clock = pygame.time.Clock()
zoneObjectSprites = pygame.sprite.RenderPlain()
while 1:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == KEYDOWN and event.key == K_ESCAPE:
return
if event.type == MOUSEBUTTONDOWN:
if event.button == 3:
#spawn a box at the cursor position
mX, mY = pygame.mouse.get_pos()
Blok.Blok(mX,mY).add(zoneObjectSprites)
#Blue background and terrain
screen.blit(background2, (0, 0))
screen.blit(background, (0, 0))
#Get the mask of the terrain
#terrainmask = pygame.mask.from_threshold(background, colour,
(1, 1, 1))
terrainmask = pygame.mask.from_surface(background)
#print the mask count to see if its big enough
print terrainmask.count()
for object in zoneObjectSprites:
object.gravity(terrainmask)
zoneObjectSprites.draw(screen)
pygame.display.flip()
#this calls the 'main' function when this script is executed
if __name__ == '__main__': main()
+-------------------------Blok class:
class Blok(pygame.sprite.Sprite):
def __init__(self, X, Y):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image('blok1.bmp',-1)
screen = pygame.display.get_surface()
self.area = screen.get_rect()
self.rect.center = X, Y
self.gravityForce = 3
self.mask = pygame.mask.from_surface(self.image,255)
print self.mask.count()
def gravity(self,terrainmask):
dy = self.mask.overlap(terrainmask,(0,0))
print dy
#did we hit the ground?
if dy is not None:
print 'hit ground'
else:
newpos = self.rect.move((0, self.gravityForce))
self.rect = newpos
#kill object if it goes offscreen
if self.rect.top > 500:
self.kill()