Camera
The Camera class in TCJSgame v3 allows you to create scrolling worlds larger than the canvas. By default, everything is drawn relative to the canvas, but with a camera you can move the "view window" across a much bigger game map. This is essential for platformers, RPGs, and side-scrollers.
To use a camera, create it with the same dimensions as your canvas. Then call camera.follow(component)
to make it track a specific object, usually the player. The camera automatically shifts the drawing origin
so that the player remains centered (or offset if you prefer). You can also move the camera manually by changing
camera.x
and camera.y
.
Syntax
const camera = new Camera(width, height);
camera.follow(component);
Example
const display = new Display();
display.start(800, 400);
const player = new Component(30, 30, "red", 100, 100, "rect");
display.add(player);
const camera = new Camera(800, 400);
camera.follow(player);
function update() {
if (display.keys[39]) player.x += 3;
if (display.keys[37]) player.x -= 3;
}
Notes
- The camera only affects drawing, not collision detection.
- Combine with
TileMap
for scrolling maps.