Camera: following the action
The Camera class handles viewport offsetting. It tracks a target with options for deadzones, smoothing (lerp), bounding boxes, and screen shake.
SETUP AND MODES
Create a camera by passing the screen dimensions. You can choose between different tracking modes like "centered" or "deadzone".
import pygame
from tilemap_parser import Camera
# 800x600 viewport
camera = Camera(800, 600, mode="deadzone")
# Set the deadzone rectangle (x, y, w, h)
camera.deadzone = pygame.Rect(300, 200, 200, 200)
# Optional: clamp the camera so it never views outside the map boundaries
# camera.set_bounds(0, 0, map_width_px, map_height_px)UPDATE AND DRAW
Tell the camera who to follow, update it every frame with dt, and then use its offset property when drawing.
# 1. Target needs x, y and collision_shape attributes
camera.follow(player)
# 2. Update camera physics (smoothing, shake)
camera.update(dt)
# 3. Use camera.offset to draw (a (x, y) tuple)
# TileLayerRenderer accepts the offset directly:
renderer.render(screen, camera.offset)
# For sprites, subtract the offset:
ox, oy = camera.offset
draw_x = player.x - ox
draw_y = player.y - oy
screen.blit(player_img, (draw_x, draw_y))SCREEN SHAKE
The camera includes a built-in screen shake effect, useful for impacts and explosions.
# Start a shake with intensity (pixels) and duration (seconds)
camera.shake(intensity=10.0, duration=0.5)