Last active
February 15, 2025 13:06
-
-
Save nitori/8d733e8c1f963dad120d850e8b428d42 to your computer and use it in GitHub Desktop.
Check if mouse position collides with the non-transparent shape of an image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import pygame | |
pygame.init() | |
screen = pygame.display.set_mode((800, 600)) | |
clock = pygame.time.Clock() | |
class Triangle(pygame.sprite.Sprite): | |
def __init__(self): | |
super().__init__() | |
# alternatively just use pygame.image.load(...).convert_alpha() | |
self.image = pygame.Surface((300, 250), pygame.SRCALPHA) | |
self.active = False | |
self.redraw((255, 0, 0)) | |
self.rect = self.image.get_rect(center=(400, 300)) # screen center | |
self.mask = pygame.mask.from_surface(self.image) | |
def redraw(self, color): | |
# this just draws the image. you don't need it if you got a static image. | |
self.image.fill((0, 0, 0, 0)) | |
w, h = self.image.get_size() | |
pygame.draw.polygon(self.image, color, [ | |
(w // 2, 0), | |
(w, h), | |
(0, h) | |
]) | |
self.mask = pygame.mask.from_surface(self.image) | |
triangle = Triangle() | |
while True: | |
clock.tick(120) | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
pygame.quit() | |
sys.exit() | |
screen.fill((0, 0, 0)) | |
screen.blit(triangle.image, triangle.rect) | |
x, y = pygame.mouse.get_pos() | |
# get the position of the mouse within the mask, could be negative | |
pos_in_mask = x - triangle.rect.x, y - triangle.rect.y | |
# check if colliding with image, and get the mask value at the position. | |
if triangle.rect.collidepoint(x, y) and triangle.mask.get_at(pos_in_mask): | |
if not triangle.active: | |
triangle.redraw((0, 255, 0)) | |
triangle.active = True | |
else: | |
if triangle.active: | |
triangle.redraw((255, 0, 0)) | |
triangle.active = False | |
pygame.display.flip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment