I’m trying to use collision detection to detect when my mouse hits an image that I’ve imported. I get the error “tuple does not have attribute rect”
def main():
#Call the SDL arg to center the window when it's inited, and then init pygame
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
#Set up the pygame window
screen = pygame.display.set_mode((600,600))
image_one = pygame.image.load("onefinger.jpg").convert()
screen.fill((255, 255, 255))
screen.blit(image_one, (225,400))
pygame.display.flip()
while 1:
mousecoords = pygame.mouse.get_pos()
left = (mousecoords[0], mousecoords[1], 10, 10)
right = image_one.get_bounding_rect()
if pygame.sprite.collide_rect((left[0]+255, left[1]+400, left[2], left[3]), right):
print('Hi')
The problem is that pygame.sprite.collide_rect() takes two Sprite objects. You are passing it two tuples – neither the cursor nor the image are Sprites and so lack a rect attribute.
You could make a Sprite using image_one, but it will be more tricky to convert the cursor into a Sprite. I think it would be easier to manually test whether the cursor is within the image.
Notice that I test whether the mouse has moved before testing whether it’s in the image, to avoid repeating the calculation needlessly.