2

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?

Rajarshi
  • 45
  • 1
  • 6

1 Answers1

2

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.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • ok so the centre will be for x will be self.x + self.img.get_width()/2 – Rajarshi Jul 16 '21 at 10:35
  • @Rajarshi Yes. Reading the documentation will clear up all of your questions: [`pygame.Rect´](https://www.pygame.org/docs/ref/rect.html) – Rabbid76 Jul 16 '21 at 10:36
  • But i have a question why we would use the .centre – Rajarshi Jul 16 '21 at 10:37
  • @Rajarshi You use center when you want to set or get the center of the image. e.g. When you want to center a rectangle on the screen. – Rabbid76 Jul 16 '21 at 10:38
  • OK but we can simply get the center of a image by self.x + self.img.get_width()/2 – Rajarshi Jul 16 '21 at 10:40
  • @Rajarshi Yes you can, but you'll need more code. See for example [How to Center Text in Pygame](https://stackoverflow.com/questions/23982907/pygame-how-to-center-text/64660744#64660744) or [How do I rotate an image around its center using PyGame?](https://stackoverflow.com/questions/4183208/how-do-i-rotate-an-image-around-its-center-using-pygame/54714144#54714144) – Rabbid76 Jul 16 '21 at 10:41