Search code examples
pythonpython-3.xobjectpygamerect

Pygame rect.centre attribute


So here is two parts of pygame python code:

a = self.img.get_rect(topleft = (self.x, self.y))
print(a.topleft)

The output of this code is :

(200, 189)

Another pygame code:

a = self.img.get_rect(topleft = (self.x, self.y)).center
print(a)

The output of this code:

(234, 213)

Note: The value of self.x is 200 and self.y is 200

So now my question is how after we put .center after the pygame rect object or the variable a when i print the value of a it changes and what does a .center after a pygame rect object do?


Solution

  • pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, but it returns a rectangle that always starts at (0, 0) since a Surface object has no position. The position of the rectangle can be specified by a keyword argument. For example, the top left of the rectangle can be specified with the keyword argument topleft.

    The pygame.Rect object has various virtual attriubtes:

    The Rect object has several virtual attributes which can be used to move and align the Rect:

    x,y
    top, left, bottom, right
    topleft, bottomleft, topright, bottomright
    midtop, midleft, midbottom, midright
    center, centerx, centery
    size, width, height
    w,h
    

    You actually set the top left corner of a rectangle, the size of the image:

    self.img.get_rect(topleft = (self.x, self.y))
    

    Finally, you get the center point of this rectangle by reading the center attribute. Since the size of the image is not 0, the center differs from the topleft.