Search code examples
pythonpygamedrawingrectangles

How to move a rect together with its associated drawing (Pygame)?


Minimal working example:

x = pygame.draw.circle(screen, color, (x, y), radius, width)
x.center = (my_wanted_center_x, my_wanted_center_y)

Then after updating the display, it's always displayed at its original location. Tried with other figures as well. Neither does x.move() work. How do I move any drawn figure in a simplest way?


Solution

  • You can use a pygame.Rect to store the position of your object, update the rect's attributes (for example .x or .center) in the while loop and then draw your circle or image/surface at the rect.center position.

    import pygame as pg
    
    pg.init()
    
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    BG_COLOR = pg.Color('gray12')
    SIENNA = pg.Color('sienna1')
    radius = 20
    # This rect serves as the position of the circle and
    # can be used for collision detection.
    rect = pg.Rect(50, 200, radius, radius)
    
    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
    
        rect.x += 1  # Update the position of the rect.
    
        screen.fill(BG_COLOR)
        # Now draw the circle at the center of the rect.
        pg.draw.circle(screen, SIENNA, rect.center, radius)
        pg.display.flip()
        clock.tick(30)
    
    pg.quit()