Reputation: 23
I'm currently writing a game in pygame. For a specific aspect of the game I would like for the user to be able to click on an image and get information. I have an array of class objects that have an image field and I loop through this array trying to see if one of the images have been clicked to display the object's info. The problem is that it only seems to work for one image, and it is the image in the middle of the array. I tried changing the variable used to get the index of the array item to a constant value to see if I can get the first image in the array to show it's info, but that didn't work, instead the middle image still responded to the click.
Run = True
while Run:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
Run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mX,mY = event.pos
for l in range(len(Locations)):
if Locations[l].board.get_rect().collidepoint((mX,mY)):
Locations[l].GetInfo()
Upvotes: 2
Views: 89
Reputation: 210968
Locations[l].board
is a pygame.Surface
object. A Surface has no location it only has a size, so get_rect()
returns a rectangle which always starts at (0, 0). You've to set the position of the rectangle manually.
e.g. If the position is stored in Locations[l].x
, Locations[l].y
, then you can do:
mX,mY = event.pos
for l in range(len(Locations)):
x, y = Locations[l].x, Locations[l].y
rect = Locations[l].board.get_rect(topleft = (x, y))
if rect.collidepoint((mX,mY)):
Locations[l].GetInfo()
Upvotes: 2