Search code examples
pythonpygamegeometry

How to slowly draw a circle in Pygame?


I want to slowly draw a circle in pygame so the act of drawing is actually visible to the naked eye. I got a function on stackoverflow to draw a straight line by incrementing the end point and keeping the starting point same but couldn't figure out how to slowly draw a circle in the pygame screen.


Solution

  • You can use the standard sine and cos circle formula:

    • x = r * cos(radians(i)) + a
    • y = r * sin(radians(i)) + b

    Where a is the x coordinate of the center of the circle, and b is the y coordinate of the center of the circle r is the radius of the circle.

    To slow down the animation, use a Clock object. You can access the functions sin and cos from the built-in math module (note that you'll need to pass in the values as radians, hence the importance of the radians function).

    The implementation:

    import pygame
    from math import sin, cos, radians
    
    pygame.init()
    wn = pygame.display.set_mode((600, 600))
    
    r = 100
    a = 300
    b = 200
    
    clock = pygame.time.Clock()
    for i in range(1, 361):
        clock.tick(30)
        pygame.draw.circle(wn, (255, 255, 255), (int(r * cos(radians(i)) + a), int(r * sin(radians(i)) + b)), 2)
        pygame.display.update()
    

    Output:

    enter image description here

    If you prefer to use standard lines as the outline instead of overlapping dots, use the pygame.draw.line function like so:

    import pygame
    from math import sin, cos, radians
    
    pygame.init()
    wn = pygame.display.set_mode((600, 600))
    
    r = 100
    a = 300
    b = 200
    
    def x_y(r, i, a, b):
        return (int(r * cos(radians(i)) + a), int(r * sin(radians(i)) + b))
    
    clock = pygame.time.Clock()
    for i in range(0, 360, 2):
        clock.tick(30)
        pygame.draw.line(wn, (255, 255, 255), x_y(r, i, a, b), x_y(r, i+1, a, b), 2)
        pygame.display.update()