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.