I'm trying to figure out how to use the area argument one can pass when blitting a pygame surface. Picture a isometric rpg view where the camera is following the character.
My code is working fine as long as my player stays in the starting screen boundaries, but as soon as we're stepping out, the player gets clipped out. Could you please help me figure out what I'm missing ?
def run(fullmap):
pygame.init()
clock=pygame.time.Clock()
screen = pygame.display.set_mode((400,400))
# - background -
fullmap_rect = fullmap.get_rect()
# - player -
player = pygame.Surface((100,100))
player.fill((255,255,255))
player_rect = player.get_rect()
player_rect.center = (200, 200)
# - camera -
camera = screen.get_rect()
camera.center = player_rect.center
# - game loop -
while 1:
clock.tick(25)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# - input management -
keys=pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
player_rect.y += 10
camera.y += 10
if keys[pygame.K_LEFT]:
player_rect.x -= 10
camera.x -= 10
if keys[pygame.K_UP]:
player_rect.y -= 10
camera.y -= 10
if keys[pygame.K_RIGHT]:
player_rect.x += 10
camera.x += 10
# - screen repaint -
screen.fill((0,0,0))
screen.blit(fullmap, (0,0), camera)
screen.blit(player, player_rect, camera)
pygame.display.flip()
if __name__ == '__main__':
RED = (150, 50, 0)
GREEN = (0, 150, 5)
BLUE = (50, 0, 150)
COLORS = (RED, GREEN, BLUE)
TILE_SIZE = 10
fullmap = pygame.Surface((1000, 1000))
for y in range(0, 1000, TILE_SIZE):
for x in range(0, 1000, TILE_SIZE):
pygame.draw.rect(fullmap, random.choice(COLORS), (x, y, TILE_SIZE, TILE_SIZE))
run(fullmap)
I'm expecting to follow my player around the entirety of the fullmap.
Thank you and have a nice day !
The optional area
argument represents a smaller portion of the source. This is useful for the game map, but not for the player. You want to draw the complete player image, not just part of it.
You have to compute the position of the player relative to the camera:
screen.blit(fullmap, (0, 0), camera)
screen.blit(player, (player_rect.x - camera.x, player_rect.y - camera.y))
However, since your player is in the center of the screen, just draw it in the center of the screen:
screen.blit(fullmap, (0, 0), camera)
screen.blit(player, player.get_rect(center = screen.get_rect().center))