Reputation: 123
I have a class of Circle It is:
import pygame
pygame.init()
import math
class Circle:
def __init__(self, circle_x, cirlce_y, circle_radius):
self.circle_x = circle_x
self.circle_y = cirlce_y
self.circle_radius = circle_radius
def clicked(self):
mouse_x, mouse_y = pygame.mouse.get_pos()
area = math.pi * self.circle_radius * self.circle_radius
print(area)
if self.circle_x - self.circle_radius <= mouse_x <= self.circle_x + self.circle_radius and self.circle_y - self.circle_radius <= mouse_y <= self.circle_y + self.circle_radius:
return True
the problem is that it is working good but when as the circle have round edges. But wheni click on the a point some distance away from the edge of the circle its still detecting that the circle is clicked. how can i omit this error and detect circle click only in the circle boundary not detecting circle as a sqaure?
Upvotes: 1
Views: 129
Reputation: 210889
You need to calculate the Euclidean distance between the center of the circle and the mouse. Test if this distance is less than the radius:
def clicked(self):
mouse_x, mouse_y = pygame.mouse.get_pos()
dx = mouse_x - self.circle_x
dy = mouse_y - self.circle_y
distance = math.sqrt(dx*dx + dy*dy) # or: distance = math.hypot(dx, dy)
return distance <= self.circle_radius
You can improve performance and get rid of the costly math.sqrt
operation by comparing the square of the distance to the square of the radius:
def clicked(self):
mouse_x, mouse_y = pygame.mouse.get_pos()
dx = mouse_x - self.circle_x
dy = mouse_y - self.circle_y
return dx*dx + dy*dy <= self.circle_radius*self.circle_radius
Upvotes: 3