# misc/camera2d (vanilla.js 0.4.0)

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

2D 카메라.

## Camera2D extends Object

2D 카메라.
- 여러 게임이 제각각 만들던 "추적 + 월드 경계 클램프 + 드래그 팬 + 커서 고정 줌 + 관성" 을 모았다.
- position 은 카메라가 바라보는 월드 좌표(화면 가운데), zoom 은 확대 배율, rotation 은 화면 가운데를 축으로 도는 각도(도)다.
  rotation 만큼 월드가 화면에서 돈다. (deprecated/camera.js 의 begin 이 scale 뒤 rotate 를 거는 것과 같은 방향)
- 사용:
    camera.setViewSize(viewSize);            // 매 프레임 또는 리사이즈 시
    camera.follow([heroPosition], 6, timeDelta);   // 추적 (선택)
    camera.tick(timeDelta);
    camera.applyTransform(graphic);          // 월드 그리기 전에
    ...월드 렌더...
    graphic.popState 는 pushState 를 쓴 쪽에서.
    또는 camera.begin(graphic); ...월드 렌더... camera.end(graphic);   // pushState + applyTransform / popState

예제: 끌어서 둘러보고 놓으면 관성으로 미끄러지는 월드

```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): 생성.
- `tick(timeDelta)` (method, since 0.3.0): 갱신. (관성 이동 + 이동 트윈 + 경계 클램프)
  - `timeDelta` number: 지난 프레임부터의 시간. (초)
- `follow(targetPositions, rate, timeDelta)` (method, since 0.3.0): 대상 추적. (여러 대상이면 중점을 따라간다, 프레임 독립 지수 감쇠)
  - `targetPositions` Vector2[]: 따라갈 대상들의 월드 위치. (빈 배열이면 그대로)
  - `rate` number: 추적 속도. (클수록 빨리 붙는다)
  - `timeDelta` number: 지난 프레임부터의 시간. (초)

  예제: 두 캐릭터의 가운데를 따라가기

  ```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): 화면 픽셀 단위 팬. (드래그 팬, 줌과 회전을 반영해 월드 이동량으로 환산)
  - `screenDeltaX` number: 화면 가로 이동량. (픽셀, 끈 만큼 그대로 넘긴다)
  - `screenDeltaY` number: 화면 세로 이동량. (픽셀, 끈 만큼 그대로 넘긴다)
- `fling(screenVelocityX, screenVelocityY)` (method, since 0.3.0): 관성 던지기. (드래그를 놓을 때 화면 픽셀 속도를 넘긴다)
  - `screenVelocityX` number: 화면 가로 속도. (픽셀 / 초)
  - `screenVelocityY` number: 화면 세로 속도. (픽셀 / 초)
- `convertScreenDeltaToWorld(screenDeltaX, screenDeltaY)` (method, since 0.4.0): 화면 픽셀 이동량 → 월드 이동량. (회전을 되돌리고 줌으로 나눈다)
  - `screenDeltaX` number: 화면 가로 이동량. (픽셀)
  - `screenDeltaY` number: 화면 세로 이동량. (픽셀)
  - returns Vector2: 월드 이동량.
- `zoomAt(anchorScreen, zoomFactor)` (method, since 0.3.0): 화면 기준점을 고정한 줌. (휠 / 핀치, anchorScreen 아래의 월드 지점이 움직이지 않는다)
  - `anchorScreen` Vector2: 화면 좌표. (뷰 좌상단 기준)
  - `zoomFactor` number: 곱할 배율. (1.1 = 10% 확대)

  예제: 커서 아래 지점을 붙잡은 채 확대하기

  ```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): 위치 / 줌으로 이동 트윈 시작.
  - `targetPosition` Vector2: 옮겨 갈 월드 위치.
  - `targetZoom` number: 옮겨 갈 배율. (줌 범위로 자른다)
  - `duration` number: 걸리는 시간. (초, 기본 0.4)

  예제: 0.5 초 동안 다른 자리로 옮겨 가며 확대하기

  ```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): 그리기 변환 적용. (호출한 쪽에서 pushState / popState 로 감싼다)
  - `graphic` Graphic: 변환을 걸 그래픽.
- `begin(graphic)` (method, since 0.4.0): 그리기 시작. (상태를 쌓고 변환을 건다, deprecated/camera.js 의 begin)
  - `graphic` Graphic: 그릴 그래픽.
- `end(graphic)` (method, since 0.4.0): 그리기 끝. (begin 이 쌓은 상태를 되돌린다, deprecated/camera.js 의 end)
  - `graphic` Graphic: 그릴 그래픽.
- `screenToWorld(screenPosition)` (method, since 0.3.0): 화면 좌표 → 월드 좌표.
  - `screenPosition` Vector2: 화면 좌표. (뷰 좌상단 기준)
  - returns Vector2: 월드 좌표.
- `worldToScreen(worldPosition)` (method, since 0.3.0): 월드 좌표 → 화면 좌표.
  - `worldPosition` Vector2: 월드 좌표.
  - returns Vector2: 화면 좌표. (뷰 좌상단 기준)
- `getVisibleHalfExtent()` (method, since 0.4.0): 화면에 보이는 월드 영역의 반 너비, 반 높이. (돌아간 뷰를 감싸는 축 정렬 상자)
  - returns Vector2: 보이는 월드 영역의 반 너비, 반 높이.
- `clampToBounds()` (method, since 0.3.0): 월드 경계로 클램프.
  - 보이는 영역이 경계 안에 들게 한다. 보이는 영역이 경계보다 크면(줌아웃) 축 가운데에 맞춘다.
  - 돌아가 있으면 돌아간 뷰를 감싸는 축 정렬 상자로 잰다.
- `setPosition(position)` (method, since 0.3.0): 바라볼 월드 위치 설정. (화면 가운데, 월드 경계가 있으면 자른다)
  - `position` Vector2: 바라볼 월드 위치. (월드 경계가 있으면 자른다)
- `getPosition()` (method, since 0.3.0): 바라보는 월드 위치 반환. (화면 가운데)
  - returns Vector2: 바라보는 월드 위치.
- `setZoom(zoom)` (method, since 0.3.0): 확대 배율 설정. (줌 범위로 자른다, 기본 1)
  - `zoom` number: 확대 배율.
- `getZoom()` (method, since 0.3.0): 확대 배율 반환.
  - returns number: 확대 배율.
- `setRotation(rotation)` (method, since 0.4.0): 회전 각도 설정.
  - `rotation` number: 도. (화면 가운데를 축으로 돈다)
- `getRotation()` (method, since 0.4.0): 회전 각도 반환. (도)
  - returns number: 회전 각도. (도)
- `setViewSize(viewSize)` (method, since 0.3.0): 화면 크기 설정. (화면 가운데를 잡는 데 쓴다, 기본 960 x 640)
  - `viewSize` Vector2: 화면 크기. (픽셀)
- `getViewSize()` (method, since 0.3.0): 화면 크기 반환.
  - returns Vector2: 화면 크기. (픽셀)
- `setWorldBounds(worldBounds)` (method, since 0.3.0): 월드 경계 설정. (보이는 영역이 이 안에 들게 자른다)
  - `worldBounds` Rect | null: 월드 경계. (null 이면 자르지 않는다)
- `getWorldBounds()` (method, since 0.3.0): 월드 경계 반환.
  - returns Rect | null: 월드 경계. (없으면 null)
- `setZoomRange(minZoom, maxZoom)` (method, since 0.3.0): 줌 범위 설정. (지금 배율도 이 범위로 자른다, 기본 0.1 ~ 8)
  - `minZoom` number: 최소 배율.
  - `maxZoom` number: 최대 배율.
- `setInertiaDamping(inertiaDamping)` (method, since 0.3.0): 관성 감쇠 설정. (클수록 빨리 멈춘다, 기본 6)
  - `inertiaDamping` number: 관성 감쇠. (초당 지수 감쇠 계수)
- `isTweening()` (method, since 0.3.0): 이동 트윈 중인지 여부.
  - returns boolean: 이동 트윈 중이면 참.
- `stopInertia()` (method, since 0.3.0): 관성 정지.
