Reputation: 59
How can I check if circle on separate surface is clicked?
from pygame.locals import *
import pygame, sys, math
pygame.init()
screen = pygame.display.set_mode((640, 480))
s = pygame.Surface((100, 100))
s.fill((255, 0, 0))
s_rect = s.get_rect(center = (300, 300))
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
x = pygame.mouse.get_pos()[0]
y = pygame.mouse.get_pos()[1]
sqx = (x - 20)**2
sqy = (y - 20)**2
if math.sqrt(sqx + sqy) < 20:
print ('inside')
screen.fill((200, 200, 255))
screen.blit(s, s_rect)
pygame.draw.circle(s, (0, 0, 0), (20, 20), 20) # this doesn't work
pygame.draw.circle(screen, (0, 0, 0), (20, 20), 20) # this works
pygame.display.update()
pygame.quit()
Nothing happens when I run this code. However if I draw the circle on the main screen it works!!!
Upvotes: 1
Views: 400
Reputation: 210948
You have to compute the mouse position relative to the Surface.
You have 2 possibilities. Either subtract the (top left) position of the Surface on the screen from the mouse position:
x = event.pos[0] - s_rect.left
y = event.pos[1] - s_rect.top
Or add the (top left) position of the Surface on the screen to the center point of the circle:
sqx = (x - (s_rect.left + 20))**2
sqy = (y - (s_rect.top + 20))**2
Complete example
from pygame.locals import *
import pygame, math
pygame.init()
screen = pygame.display.set_mode((640, 480))
s = pygame.Surface((100, 100))
s.fill((255, 0, 0))
s_rect = s.get_rect(center = (300, 300))
clicked = False
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
x = event.pos[0]
y = event.pos[1]
sqx = (x - (s_rect.left + 20))**2
sqy = (y - (s_rect.top + 20))**2
if math.sqrt(sqx + sqy) < 20:
clicked = not clicked
print ('inside')
screen.fill((200, 200, 255))
color = (255, 255, 255) if clicked else (0, 0, 0)
pygame.draw.circle(s, color, (20, 20), 20)
screen.blit(s, s_rect)
pygame.display.update()
pygame.quit()
Upvotes: 1