'Issue with camera tracking in pygame
So I'm following a youtube tutorial that uses a tile-map. A camera that tracks the player moving horizontally was added and I implemented a vertical camera as well, these both work well. The issue I'm having is that the player spawns in the bottom left-hand corner of the map off-screen, while the camera view starts in the top left-hand corner. Therefore at the beginning of the game I have to wait a few seconds for the camera to slowly move down screen to get the player in view. My question is how do I get the camera to start with the player already in view? Thanks in advance
Tile Class:
class Tile(pygame.sprite.Sprite):
def __init__(self,image, pos,size):
super().__init__()
file = pygame.image.load(image)
self.image = pygame.transform.scale(file, (96, 96))
self.rect = self.image.get_rect(bottomleft = pos)
def update(self,x_shift, y_shift):
self.rect.x += x_shift
self.rect.y += y_shift
Scroll Function:
def scroll(self):
player = self.player.sprite
player_x = player.rect.centerx
player_y = player.rect.centery
direction_x = player.direction.x
if player_x < screen_width / 4 and direction_x < 0:
self.world_shift_x = 8
player.speed = 0
elif player_x > screen_width - (screen_width / 4) and direction_x > 0:
self.world_shift_x = -8
player.speed = 0
else:
self.world_shift_x = 0
player.speed = 8
if player_y < screen_height / 4 :
self.world_shift_y = 8
elif player_y > screen_height - (screen_height / 4):
self.world_shift_y = -8
else:
self.world_shift_y = 0
Update level:
self.tiles.update(self.world_shift_x, self.world_shift_y)
Solution 1:[1]
You have to initialize world_shift_x and world_shift_y and shift the tiles once before running the application loop. Run the following code before the application loop
self.world_shift_x = screen_width // 2 - player.rect.centerx
self.world_shift_y = screen_height // 2 - player.rect.centery
self.tiles.update(self.world_shift_x, self.world_shift_y)
player.rect.centerx = screen_width // 2
player.rect.centery = screen_height // 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rabbid76 |
