Umesh Konduru
Umesh Konduru

Reputation: 358

How do I draw a rectangle at the center of another rectangle in pygame?

I have a rectangle, say, rect1 . I have another rectangle called rect2. I want to blit 'rect2' such that the center of rect2 is same as that of rect1?

Upvotes: 3

Views: 9173

Answers (1)

skrx
skrx

Reputation: 20438

Just assign the center coordinates of rect1 to the center of rect2.

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')

rect1 = pg.Rect(200, 100, 161, 100)
rect2 = pg.Rect(0, 0, 120, 74)
rect2.center = rect1.center

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    screen.fill(BG_COLOR)
    pg.draw.rect(screen, (0, 100, 255), rect1, 2)
    pg.draw.rect(screen, (255, 128, 0), rect2, 2)
    pg.display.flip()
    clock.tick(60)

Upvotes: 5

Related Questions