Handmade Web Games

Chapter 6: Cameras and viewports

Placeholder.

  • intro centering a chess board on a resizable canvas
  • world space vs screen space
  • translating and zooming the canvas
  • camera smoothing?
  • screen shake
  • parallax

https://gist.github.com/onsclom/6fd127684a145861fba43ac7eca4d888 https://github.com/onsclom/ld59/blob/main/src/camera.ts

function worldToLocal(x: number, y: number, originX: number, originY: number, angle: number) {
  const cos = Math.cos(-angle);
  const sin = Math.sin(-angle);

  x -= originX;
  y -= originY;

  return {
    x: x * cos - y * sin,
    y: x * sin + y * cos,
  };
}

function localToWorld(x: number, y: number, originX: number, originY: number, angle: number) {
  const cos = Math.cos(angle);
  const sin = Math.sin(angle);

  return {
    x: x * cos - y * sin + originX,
    y: x * sin + y * cos + originY,
  };
}

compare above to the DOMPoint version

export function worldToScreen(
  worldX: number,
  worldY: number,
  ctx: CanvasRenderingContext2D,
  camera: Camera,
) {
  const canvasRect = ctx.canvas.getBoundingClientRect();
  const matrix = getTransformMatrix(canvasRect, camera, false);
  const point = new DOMPoint(worldX, worldY);
  const screenPoint = point.matrixTransform(matrix);
  return { x: screenPoint.x, y: screenPoint.y };
}