[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [pygame] collision bug?



alex wrote:
>>>>import pygame
>>>>r1=pygame.Rect((0,0,10,10))
>>>>r2=pygame.Rect((0,10,10,10))
>>>>print r1.colliderect(r2)
> 0
> 
>>>>print r1.bottom, r2.top
>>>
> 10 10
> 
> they have overlapping edges, isn't that a collision?
> sounds like there is a > instead of a >= comparision.


a tricky little situation. a little experimenting will show that the 
rectangles in pygame do not really include the "bottom" and "right" 
edges. once you get used to this setup, it actually works pretty well.

i've included a rough example that draws two rectangles, and you'll see 
the "shared" edge doesn't really overlap.

this is the way most gui toolkits also work in their layout. it allows 
you to easily layout objects right next to each other, with nothing 
overlapping. by using rectangles like this all the 'math' still works 
out in very 'human' terms..

	>>> r = pygame.Rect(10, 10, 10, 10)
	>>> print r.left, r.right
	(10, 20)
	>>> print r.right - r.left
	10

there's other locations where this type of layout for Rectangles works 
really well. obviously there are also times when it can get a little 
confusing, but once you know what really happens it is easy enough to 
resolve.

#!/usr/bin/env python
#quick and dirty to show non-overlap...

from pygame import *

init()
win = display.set_mode((200,200))

r1 = Rect(0,0,100,100)
r2 = Rect(50,100,100,100)

win.fill((100,100,200), r1)
win.fill((200,100,100), r2)

display.flip()
while 1:
    if event.wait().type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN): break