Python Forum

Full Version: pygame blit() method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
why when I put the second argument of the blit() method with surf.get_rect() the image becomes in the upper left corner of the screen? When I change the integer value it remains at the top left corner of the screen ... but when I replace the argument with (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) it changes place to almost in the middle of the screen

import pygame
from pygame.locals import (
    K_UP,
    K_DOWN,
    K_LEFT,
    K_RIGHT,
    K_ESCAPE,
    KEYDOWN,
    QUIT,
)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600


class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.surf = pygame.Surface((75, 25))
        self.surf.fill((255, 255, 255))
        self.rect = self.surf.get_rect()


pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

player = Player()

running = True

while running:

    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False

    screen.fill((0, 0, 0))

    screen.blit(player.surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
    
    pygame.display.flip()

pygame.quit()
The blit function will draw your player surface at the coordinates you give it. So if you put (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) then it will draw it there.

By saying surf.get_rect() you are just creating a rectangle from the surface, but the surface hasn't moved, so it will stay at 0,0 unless you give it new coordinates.

If you are trying to move the rectangle with the arrow keys then you can move the rectangle instead. Try adding this function to your player class:

def update(self):
        #get key press and adjust rectangle
        key = pygame.key.get_pressed()
        if key[pygame.K_RIGHT]:
            self.rect.x += 1
        if key[pygame.K_LEFT]:
            self.rect.x -= 1
        if key[pygame.K_UP]:
            self.rect.y -= 1
        if key[pygame.K_DOWN]:
            self.rect.y += 1

        screen.blit(self.surf, self.rect)
and then replace your screen.blit(player.surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)) in the game loop with player.update()


This isn't the cleanest way to do this, but it may help explain what is going on. You just take key presses and then adjust the position of the rectangle of the player instance. Then you blit your surface at those coordinates