Python Forum
[PyGame] why the position of the object is different?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] why the position of the object is different?
#1
I tried changing the object's position with the center of get_rect () and I got a different result without using center and using center

My game screen size: 400, 300

This code changes the object to the center of the screen:
text_rect_obj = text_surface_obj.get_rect()
print(text_rect_obj)
text_rect_obj.center = (200, 150)
print(text_rect_obj)
and this code creates the object close to the edge of the screen:
text_rect_obj = text_surface_obj.get_rect()
print(text_rect_obj)
text_rect_obj = (200, 150)
print(text_rect_obj)
my question is what does the center do and what is the correct position with coordinates 200, 150 at the edge of the screen or in the middle of the screen?
Reply
#2
These two assignments are completely different:
Quote:
text_rect_obj.center = (200, 150)
text_rect_obj = (200, 150)

The first one is correct. You assign a tuple x and y coordinates to the center attribute of the rect object. The second one is incorrect. In the second one you are re-assigning the rect object into just a tuple. It no longer is a pygame rect object, but a simple tuple. There is no identification on what to do with those coordinates anyways. Are those topleft coordinates? Center coordinates? Bottmleft coordinates, etc.? Now that pygame has no rect object it would put the object in the default location which happens to be the topleft of the window. a Pygame rect takes 4 arguments left postition top position, width and height in the following forms...
Quote:Rect(left, top, width, height) -> Rect
Rect((left, top), (width, height)) -> Rect

Whenever you assign a position or move an object you always use the rect in the way you did in the first example. There are more than just center...
Quote:x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h


If you want the object in the top left you would do
text_rect_obj.topleft = (0,0)
A better way to center the object on the screen is to make a rect for your screen too.
screen = pygame.display.set_mode((400, 300))
screen_rect = screen.get_rect()
...
text_rect_obj.center = screen_rect.center #assigns the center screen coordinates to the center text rect object without hardcoding
If you want the object to the topright then you would just do
text_rect_obj.topright = screen_rect.topright
syafiq14 likes this post
Recommended Tutorials:
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020