[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Re: BOUNCE pygame-users@seul.org: Non-member submission from [MarkusBopp <markus.bopp@smail.inf.fh-bonn-rhein-sieg.de>]



I have a problem with checking rects overlapping.
I use this slow procedure to test if collision works:

for shot in shotlist:
for opp in opplist:
print opp.img.get_rect().colliderect( shot.img.get_rect() )

the problem is that colliderect always returns the index '1' although no rects overlapped.
i assume you are not worried about optimizing this collision detection for now, but there is a lot of simple work you can do for this 'slow procedure'.

your problem is you are checking for collision against the image rectangles. image rectangles always start at (0, 0) and have width and height the same as the image. your image rectangles will always overlap (unless perhaps one image is sized 0? but i don't believe SDL allows that)

it's likely your objects have some sort of position attribute. if that represents the topleft corner your code should look more like this

for shot in shotlist:
shotrect = shot.img.get_rect().move(shot.position)
for opp in opplist:
opprect = opp.img.get_rect().move(opp.position)
print opprect.colliderect(shotrect)

the bad news is that this will be even a bit slower. the good news is it's almost easier to optimize for more speed.