polygoncollider2d – Pygame polygon click detection

I am currently using PyGame to build a small RPG game project, and I can personally attest that there is no built-in way to do this, at least nothing that I could find in the documentation or forums. Which is obviously very annoying and took me a long time to figure out.

The way I solved it was by:

1. Having a game loop that detects all hardware inputs from the mouse or keyboard:

for event in pygame.event.get():

2. Checking if a particular event is a mouse click event:

if event.type == pygame.MOUSEBUTTONUP:

3. Getting the position on screen where the mouse clicked:

pygame.mouse.get_pos()

4. Checking if anything with a special “clickable” attribute is on the screen at that position, and doing appropriate actions. For example, if I wanted to check for a particular object to see if the cursor was over that object at the moment of the click, I would do:

if clickableObject.collidepoint(mousePosition):

Hopefully this helps!


Edit: I reread your question and am now realizing you wanted to know specifically about polygon detection, rather than general shape detection. Apologies if I was not answering your specific question. You may want to use something like Box2D for anything more complicated than a rectangular collision area, but most polygons should just be a matter of doing some more math.