# misc/camera2d (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/misc/camera2d/

2D camera.

## Camera2D extends Object

2D camera.
- Gathers the "follow + world bounds clamp + drag pan + cursor-anchored zoom + inertia" that several games each built.
- position is the world coordinate the camera looks at (screen center), zoom is the magnification, rotation is the angle (degrees) around the screen center.
  The world rotates on screen by rotation. (same direction as begin in deprecated/camera.js applying rotate after scale)
- Usage:
    camera.setViewSize(viewSize);            // every frame or on resize
    camera.follow([heroPosition], 6, timeDelta);   // follow (optional)
    camera.tick(timeDelta);
    camera.applyTransform(graphic);          // before drawing the world
    ...world render...
    graphic.popState is done by whoever used pushState.
    or camera.begin(graphic); ...world render... camera.end(graphic);   // pushState + applyTransform / popState

Example: A world you drag to look around that glides on with inertia when released

```js
import { Engine, EngineConfiguration, Scene, Camera2D, Rect, Vector2, Colors } from "./build/vanilla.js";

const camera = new Camera2D();
camera.setWorldBounds(Rect.create(0, 0, 2000, 1200));
camera.setPosition(Vector2.create(1000, 600));
let lastTouchPosition = null;
let lastTouchVelocity = Vector2.zero();

class MainScene extends Scene {
	tick(timeDelta) {
		super.tick(timeDelta);
		const engine = this.getEngine();
		const viewManager = engine.getViewManager();
		const viewSize = viewManager.getViewSize();
		camera.setViewSize(viewSize);
		camera.tick(timeDelta);
	}

	draw(graphic) {
		camera.begin(graphic);
		graphic.setFillColor(Colors.white);
		for (let column = 0; column < 10; ++column) {
			for (let row = 0; row < 6; ++row) {
				if ((column + row) % 2 === 0) {
					graphic.drawRect(Rect.create(column * 200, row * 200, 200, 200));
				}
			}
		}
		camera.end(graphic);
		super.draw(graphic);
	}

	touchPress(viewInputPosition) {
		super.touchPress(viewInputPosition);
		camera.stopInertia();
		lastTouchPosition = viewInputPosition.clone();
	}

	touchMove(viewInputPosition) {
		super.touchMove(viewInputPosition);
		if (lastTouchPosition === null) {
			return;
		}
		const delta = viewInputPosition.subtract(lastTouchPosition);
		camera.panByScreen(delta.x, delta.y);
		lastTouchVelocity = delta.multiply(60);
		lastTouchPosition = viewInputPosition.clone();
	}

	touchRelease(viewInputPosition) {
		super.touchRelease(viewInputPosition);
		camera.fling(lastTouchVelocity.x, lastTouchVelocity.y);
		lastTouchPosition = null;
	}
}

const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.3.0): Constructor.
- `tick(timeDelta)` (method, since 0.3.0): Update. (inertial movement + move tween + bounds clamp)
  - `timeDelta` number: Time since the last frame. (Seconds)
- `follow(targetPositions, rate, timeDelta)` (method, since 0.3.0): Follows targets. (follows the midpoint of multiple targets, frame-independent exponential decay)
  - `targetPositions` Vector2[]: World positions of the targets to follow. (unchanged if the array is empty)
  - `rate` number: Follow speed. (larger catches up faster)
  - `timeDelta` number: Time since the last frame. (Seconds)

  Example: Follow the midpoint of two characters

  ```js
  import { Camera2D, Vector2 } from "./build/vanilla.js";
  
  const camera = new Camera2D();
  const heroPosition = Vector2.create(400, 300);
  const friendPosition = Vector2.create(600, 300);
  for (let frame = 0; frame < 60; ++frame) {
  	camera.follow([heroPosition, friendPosition], 6, 1 / 60);
  	camera.tick(1 / 60);
  }
  const position = camera.getPosition();
  console.log(position.x.toFixed(1), position.y.toFixed(1));
  ```

- `panByScreen(screenDeltaX, screenDeltaY)` (method, since 0.3.0): Pans in screen pixels. (drag pan, converted to world movement accounting for zoom and rotation)
  - `screenDeltaX` number: Horizontal screen movement. (pixels, pass the dragged amount as is)
  - `screenDeltaY` number: Vertical screen movement. (pixels, pass the dragged amount as is)
- `fling(screenVelocityX, screenVelocityY)` (method, since 0.3.0): Inertial fling. (pass the screen pixel velocity when releasing a drag)
  - `screenVelocityX` number: Horizontal screen velocity. (pixels / second)
  - `screenVelocityY` number: Vertical screen velocity. (pixels / second)
- `convertScreenDeltaToWorld(screenDeltaX, screenDeltaY)` (method, since 0.4.0): Screen pixel movement → world movement. (undoes rotation and divides by zoom)
  - `screenDeltaX` number: Horizontal screen movement. (pixels)
  - `screenDeltaY` number: Vertical screen movement. (pixels)
  - returns Vector2: World movement.
- `zoomAt(anchorScreen, zoomFactor)` (method, since 0.3.0): Zoom anchored at a screen point. (wheel / pinch, the world point under anchorScreen does not move)
  - `anchorScreen` Vector2: Screen coordinates. (relative to the top-left of the view)
  - `zoomFactor` number: Multiplier. (1.1 = 10% zoom in)

  Example: Zoom in while keeping the point under the cursor fixed

  ```js
  import { Camera2D, Vector2 } from "./build/vanilla.js";
  
  const camera = new Camera2D();
  camera.setViewSize(Vector2.create(960, 640));
  const cursorPosition = Vector2.create(800, 100);
  const before = camera.screenToWorld(cursorPosition);
  camera.zoomAt(cursorPosition, 1.5);
  const after = camera.screenToWorld(cursorPosition);
  console.log(camera.getZoom(), before.x, before.y, after.x, after.y);
  ```

- `tweenTo(targetPosition, targetZoom, duration = 0.4)` (method, since 0.3.0): Starts a move tween to a position / zoom.
  - `targetPosition` Vector2: World position to move to.
  - `targetZoom` number: Zoom to move to. (clamped to the zoom range)
  - `duration` number: Duration. (seconds, default 0.4)

  Example: Move to another spot while zooming in over 0.5 seconds

  ```js
  import { Camera2D, Vector2 } from "./build/vanilla.js";
  
  const camera = new Camera2D();
  camera.tweenTo(Vector2.create(300, 200), 2, 0.5);
  while (camera.isTweening()) {
  	camera.tick(1 / 60);
  }
  const position = camera.getPosition();
  console.log(position.x, position.y, camera.getZoom());
  ```

- `applyTransform(graphic)` (method, since 0.3.0): Applies the drawing transform. (the caller wraps it with pushState / popState)
  - `graphic` Graphic: Graphic to apply the transform to.
- `begin(graphic)` (method, since 0.4.0): Begins drawing. (pushes state and applies the transform, begin in deprecated/camera.js)
  - `graphic` Graphic: Graphic to draw with.
- `end(graphic)` (method, since 0.4.0): Ends drawing. (restores the state pushed by begin, end in deprecated/camera.js)
  - `graphic` Graphic: Graphic to draw with.
- `screenToWorld(screenPosition)` (method, since 0.3.0): Screen coordinates → world coordinates.
  - `screenPosition` Vector2: Screen coordinates. (relative to the top-left of the view)
  - returns Vector2: World coordinates.
- `worldToScreen(worldPosition)` (method, since 0.3.0): World coordinates → screen coordinates.
  - `worldPosition` Vector2: World coordinates.
  - returns Vector2: Screen coordinates. (relative to the top-left of the view)
- `getVisibleHalfExtent()` (method, since 0.4.0): Half width and half height of the world area visible on screen. (axis-aligned box enclosing the rotated view)
  - returns Vector2: Half width and half height of the visible world area.
- `clampToBounds()` (method, since 0.3.0): Clamps to the world bounds.
  - Keeps the visible area inside the bounds. If the visible area is larger than the bounds (zoomed out), centers it on that axis.
  - When rotated, measures with the axis-aligned box enclosing the rotated view.
- `setPosition(position)` (method, since 0.3.0): Sets the world position to look at. (Screen center, clamped to the world bounds if any)
  - `position` Vector2: World position to look at. (clamped if world bounds are set)
- `getPosition()` (method, since 0.3.0): Returns the world position being looked at. (center of the screen)
  - returns Vector2: World position being looked at.
- `setZoom(zoom)` (method, since 0.3.0): Sets the zoom. (clamped to the zoom range, default 1)
  - `zoom` number: Zoom factor.
- `getZoom()` (method, since 0.3.0): Returns the zoom.
  - returns number: Zoom factor.
- `setRotation(rotation)` (method, since 0.4.0): Sets the rotation angle.
  - `rotation` number: Degrees. (rotates around the screen center)
- `getRotation()` (method, since 0.4.0): Returns the rotation angle. (degrees)
  - returns number: Rotation angle. (degrees)
- `setViewSize(viewSize)` (method, since 0.3.0): Sets the screen size. (used to find the screen center, default 960 x 640)
  - `viewSize` Vector2: Screen size. (pixels)
- `getViewSize()` (method, since 0.3.0): Returns the screen size.
  - returns Vector2: Screen size. (pixels)
- `setWorldBounds(worldBounds)` (method, since 0.3.0): Sets the world bounds. (clamps so the visible area stays inside)
  - `worldBounds` Rect | null: World bounds. (no clamping if null)
- `getWorldBounds()` (method, since 0.3.0): Returns the world bounds.
  - returns Rect | null: World bounds. (null if none)
- `setZoomRange(minZoom, maxZoom)` (method, since 0.3.0): Sets the zoom range. (also clamps the current zoom to this range, default 0.1 ~ 8)
  - `minZoom` number: Minimum zoom.
  - `maxZoom` number: Maximum zoom.
- `setInertiaDamping(inertiaDamping)` (method, since 0.3.0): Sets the inertia damping. (larger stops sooner, default 6)
  - `inertiaDamping` number: Inertia damping. (exponential decay coefficient per second)
- `isTweening()` (method, since 0.3.0): Whether a move tween is running.
  - returns boolean: True while a move tween is running.
- `stopInertia()` (method, since 0.3.0): Stops inertia.
