Jhpark0303
Jhpark0303

Reputation: 13

Centering the Images

I just started Pygame this year, and I'm currently making a clicker game using pygame. For some reason, the image is not centering on the screen.

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((2560, 1760))
    
class emoji:
     def __init__(self, x, y):
         self.x=x
         self.y=y
         self.length = 500
         self.emoji = pygame.transform.scale(pygame.image.load("emoji.jpeg"), (self.length, self.length))
    
     def draw(self):
         screen.blit(self.emoji, (self.x, self.y))
    
     def rect(self):
         self.rect_.x=self.x
         self.rect_.y=self.y
         return self.rect_


    
while True:
    screen.fill((255, 255, 255))

    # this is the problematic line:
 
    obj = emoji(screen.get_rect().center[0], screen.get_rect().center[1])

    obj.draw()
    pygame.display.flip()

    for x in pygame.event.get():
       if x.type == pygame.QUIT:
           sys.exit()

That's my code, and obj=emoji(screen.get_rect().center[0], screen.get_rect().center[1]) is my centering code. I have no idea what is wrong with it. According to every single source I have, that is how to center an object.

Upvotes: 1

Views: 406

Answers (1)

Rabbid76
Rabbid76

Reputation: 210880

Get the bounding rectangle of the image and set the center of the rectangle to the center of the screen. Use the rectangle to blit the image:

screen.blit(self.emoji, (self.x, self.y))

screen.blit(self.emoji, self.emoji.get_rect(center = (self.x, self.y)))

Note, the 2nd argument of blit can either be a tuple with the coordinates or a rectangle. When the argument is a rectangle, the upper left corner of the rectangle will be used as the position for the blit.

Upvotes: 1

Related Questions