0
votes

I'm attempting to create a top-down game using Pygame. I have a solid grasp on the basic concepts of Python, but I have very little experience creating programs without instruction of some sort. I've decided to use a fairly large map that scrolls in the background with the character remaining in the center of the view, and I've accomplished that, but my attempts to change the sprite behaviors when the character is close to the edge of the map have failed thus far.

I am attempting to change the sprite behavior so the edge of the background doesn't scroll past the edge of the window and instead the sprite starts moving within the window toward the edge of the background. I understand this probably isn't very clear, but here's some code to show my attempts thus far.

class Player(pygame.sprite.Sprite):
def __init__(self,*groups):
    super(Player,self).__init__(*groups)
    self.image = pygame.image.load('player.png')
    # Sets start position
    self.rect = pygame.rect.Rect((0,0),self.image.get_size())

#Logging player key presses
def update(self,dt):
    last = self.rect
    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT]:
        self.rect.x += 300 * dt
    if key[pygame.K_RIGHT]:
        self.rect.x -= 300 * dt
    if key[pygame.K_UP]:
        self.rect.y += 300 * dt
    if key[pygame.K_DOWN]:
        self.rect.y -= 300 * dt

    new = self.rect
    self.groups()[0].camera_x = self.rect.x - 320
    self.groups()[0].camera_y = self.rect.y - 240
    # An attempt at stopping camera movement at edges and corners
    if last.x > -320 and new.x < -320:
        self.rect.x = -320
    if last.x < 320 and new.x > 320:
        self.rect.x = 320
    if last.y > -240 and new.y < -240:
        self.rect.y = -240
    if last.y < 240 and new.y > 240:
        self.rect.y = 240

That's the player code, and here's a snippet from the Game class.

class Game(object):
def main(self,screen):
    clock = pygame.time.Clock()

    background = pygame.image.load('background.png')
    sprites = ScrolledGroup()
    sprites.camera_x = 360
    sprites.camera_y = 240
    self.player = Player(sprites)

    while 1:
    . . .
    screen.blit(background, (sprites.camera_x,sprites.camera_y))

Obviously there's other code in and around this, but I think this is everything pertaining to my question.

1

1 Answers

0
votes

Have you tried checking the camera bounds as well as the player bounds? Say your screen is 640 x 480

i.e. after you move the camera, see if it is farther than you'd like it to go:

self.groups()[0].camera_x = self.rect.x - 320
if self.groups()[0].camera_x < -320: #half the screen width, so we want the player to move towards this now
    self.groups()[0].camera_x = -320

Do the same for the camera_y based on the boundaries as well as camera_x for the other end (SCREEN_WIDTH + ( SCREEN_WIDTH / 2)).

Then check to make sure your player isn't walking over the edge of the screen.