2

So, I'm making a 2d topviewed game in Python with Pygame. I've been trying to create a camera movement that would keep the player in the center of the screen. How would I do this? I'd like to have the "map" in a single surface, that will be blit to the screen surface. If doing so I could just build the map once and then just somehow adjust it's position so that the player will always stay in the center of the screen. My player updates it's position like this:

   def update(self, dx=0, dy=0):
        newpos = (self.pos[0] + dx, self.pos[1] + dy)  # Calculates a new position
        entityrect = pygame.Rect(newpos, self.surface.get_size())  # Creates a rect for the player
        collided = False
        for o in self.objects:  # Loops for solid objects in the map
            if o.colliderect(entityrect):
                collided = True
                break

        if not collided:
            # If the player didn't collide, update the position
            self.pos = newpos

        return collided

I found this, but that was for a sideviewed platformer. So my map would look something like this:

map1 = pygame.Surface((3000, 3000))
img = pygame.image.load("floor.png")
for x in range(0, 3000, img.get_width()):
    for y in range(0, 3000, img.get_height()):
        map1.blit(img, (x, y))

So how would I do the camera movement? Any help would be appreciated.

PS. I hope you can understand what I'm asking here, english is not my native language. =)

Community
  • 1
  • 1
  • 1
    If you want to keep your player in the center of the screen at all times, then "moving the player" should actually just move the map in the opposite way. If the player is supposed to strafe right a distance `x`, then shift the map left a distance `-x`. The answer by Darthfett in the link you provided seems very relevant. – wflynny Aug 16 '13 at 15:41
  • Have you looked at this answer: [How to add scrolling to a platformer in pygame?](http://stackoverflow.com/questions/14354171/how-to-add-scrolling-to-a-platformer-in-pygame/14357169#14357169) – sloth Aug 16 '13 at 21:08

1 Answers1

2

Well, you didn't show how you draw your map or your player, but you can do something like this:

camera = [0,0]
...
def update(self, dx=0, dy=0):
    newpos = (self.pos[0] + dx, self.pos[1] + dy)  # Calculates a new position
    entityrect = pygame.Rect(newpos, self.surface.get_size())
    camera[0] += dx
    camera[1] += dy
    ...

Then you draw your map like this

screen.blit(map1, (0,0), 
            (camera[0], camera[1], screen.get_width(), screen.get_height())
           )

This way the map will scroll in the opposite direction of the camera, leaving the player still.

If you wan't the player to move in your world, but not to move in the screen, you can do something like this:

screen.blit(player, (player.pos[0]-camera[0], player.pos[1]-camera[1]))
Joe Junior
  • 176
  • 5