Dysprosium Dysprosium
Dysprosium Dysprosium

Reputation: 13

(Pygame / Python) How do I place an object on my screen based on the middle of its rect?

I thought I could simply do this:

self.rect = self.image.get_rect(center=((self.pos_x, self.pos_y)))

But that seems to have the same effect as:

self.rect = self.image.get_rect(bottomleft=((self.pos_x, self.pos_y)))

What am I missing? Both objects go in as if the (pos_x, pos_y) tuple was describing its lower left corner.

Upvotes: 1

Views: 1326

Answers (1)

nabil london
nabil london

Reputation: 521

Don't pass arguments to the method self.image.get_rect(), it returns a pygame.Rect object which has many attributes: top, bottom, left, right, topleft, topright, bottomleft, bottomright, size, width, height, center, centerx, centery, midleft, midright, midtop, midbottom #(this is from pygame docs) which you can use to place your sprite at any position in the screen, for example here you place the sprite just in the middle of the screen:

def __init__(self, screen): 
    #Load image
    #...
    self.screen = screen

    self.rect =self.image.get_rect()
    self.screen_rect = self.screen.get_rect()

    self.rect.centerx = self.screen_rect.centerx
    self.rect.centery = self.screen_rect.centery

I hope that helped.

Upvotes: 2

Related Questions