Moving Camera in PyGame

I wanted to have a moving camera in Eccoes so that the player could explore levels that were way bigger than my default screen size.

My first attempt was to see how this was done elsewhere. I followed a tutorial in “Making Games With Python and Pygame” book, chapter 8, has a simple game with a moving camera. I saw that they weren’t using sprite groups for drawing, and I realized I could benefit from that.

The problem with using sprite groups is that the Sprite.rect object is used to determine where to draw each of your sprites. This makes things very difficult when having a moving camera, since you would need to offset the position of each one of your sprites whenever the camera moved. Instead, I decided to keep the Sprite.rect objects in my world coordinates, and my drawing method would translate them onto the screen.

I created a Rect object to represent the camera. It would have dimensions that are the same size as my window, and would be locked to the center of my main player character. My update method on the level looks like:

Then my drawing code was changed from


I get a list of objects that are inside the camera rect, and then draw them to screen, shifting them according to the camera coordinates.

This works really well, and meant I didn’t have to go to any crazy schemes to get a moving camera. I may play around with getting a camera that doesn’t move immediately when the player moves, but that would only involve improvements to the update code and not to the actual drawing code. 

This entry was posted in Eccoes, Neat Tricks. Bookmark the permalink.

One Response to Moving Camera in PyGame

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.