gale.camera module
gale.camera: a 2D scrolling/zooming camera — pygame has no GPU transform stack to push a matrix onto, so a Camera turns world coordinates into screen ones instead, for you to blit with.
Author: Alejandro Mujica (aledrums@gmail.com)
- class gale.camera.Camera(viewport_width, viewport_height, x=0.0, y=0.0, zoom=1.0, bounds=None)[source]
Bases:
objectUsage example:
camera = Camera(settings.VIRTUAL_WIDTH, settings.VIRTUAL_HEIGHT) camera.follow(player, rate=6.0) # smoothly, rather than snapping every frame camera.bounds = pygame.Rect(0, 0, world_width, world_height)
# In your state: def update(self, dt):
camera.update(dt)
- def render(self, surface):
- for entity in entities:
surface.blit(entity.image, camera.apply(entity.rect))
x/y are the world point the camera is centered on — set directly for a snap-cut (a new room, a teleport), or drive with follow() for it to track a moving target on its own every update().
- Parameters:
viewport_width (float)
viewport_height (float)
x (float)
y (float)
zoom (float)
bounds (Rect | None)
- follow(target, rate=None)[source]
- Parameters:
target – Any object with x/y attributes (e.g. a gale.physics.Node, or your own player/sprite) to track every update(). Read once per update() call, so moving the target elsewhere works with no extra wiring.
rate (float | None) – How fast the camera catches up to the target, in roughly “fraction closed per second” (a higher rate is snappier; something like 4.0-10.0 reads as a smooth follow). The default value is None, snapping to the target’s position exactly every update() instead (no smoothing).
- Return type:
None
- unfollow()[source]
Stop tracking whatever target was passed to follow(), if any. x/y stay wherever they last were and are no longer moved automatically.
- Return type:
None
- shake(magnitude, duration)[source]
Start a screen shake: a random offset, in world units, applied on top of x/y, its magnitude decaying linearly to 0 over duration seconds. Calling this again while a shake is already running replaces it (they don’t stack).
- Parameters:
magnitude (float) – The maximum offset, in world units, at the very start of the shake.
duration (float) – How long, in seconds, the shake lasts.
- Return type:
None
- property offset: Tuple[float, float]
The world coordinate of the visible viewport’s top-left corner, shake included.
- Type:
returns
- world_to_screen(point)[source]
- Parameters:
point (Tuple[float, float]) – A point in world coordinates.
- Returns:
Where that point falls on screen, given this camera’s current position/zoom.
- Return type:
Tuple[float, float]
- screen_to_world(point)[source]
- Parameters:
point (Tuple[float, float]) – A point in screen coordinates (e.g. a rescaled mouse position).
- Returns:
The world coordinate under that screen point — the inverse of world_to_screen, for turning a click into “what world entity is under the mouse”.
- Return type:
Tuple[float, float]