Reputation: 47
I'm a relatively new python developer, and I stumbled across a problem. I could not get the pygame.sprite.collide_rect() function to work, and I couldnt find any solutions on the web. here's my code:
import sys
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((600,600))
pygame.display.set_caption('Doge Adventures')
gameexit = False
white = (255,255,255)
black = (0,0,0)
move_x = 300
move_y = 300
def checkCollision(sprite1, sprite2):
col = pygame.sprite.collide_rect(sprite1,sprite2)
if col == True:
sys.exit()
while not gameexit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameexit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 15
elif event.key == pygame.K_RIGHT:
move_x += 15
elif event.key == pygame.K_UP:
move_y -= 15
elif event.key == pygame.K_DOWN:
move_y += 15
gameDisplay.fill(white)
b1 = pygame.draw.rect(gameDisplay, black, [move_x, move_y, 40, 40])
b2 = pygame.draw.rect(gameDisplay, black, [450 , 450, 50, 50])
b1,b2
checkCollision(b1,b2)
pygame.QUIT()
quit()
and the error I get is:
Traceback (most recent call last):
File "C:\Users\DEREK\My Documents\LiClipse Workspace\Doge Adventures\Game.py", line 45, in <module>
checkCollision(b1,b2)
File "C:\Users\DEREK\My Documents\LiClipse Workspace\Doge Adventures\Game.py", line 19, in checkCollision
col = pygame.sprite.collide_rect(sprite1,sprite2)
File "C:\Python26\lib\site-packages\pygame\sprite.py", line 1147, in collide_rect
return left.rect.colliderect(right.rect)
AttributeError: 'pygame.Rect' object has no attribute 'rect'
Btw, I'm using python 2.7
Upvotes: 1
Views: 779
Reputation: 3814
The pygame.sprite.colliderect
method is for checking collisions between sprites, not rectangles as you are using. Sprites are instances of the pygame.sprite.Sprite
class. What you are trying to detect collisions between are rectangles, which have there own collision detection method: b1.colliderect(b2)
. Rectangles are not sprites and sprites are not rectangles.
Upvotes: 1