vanilladocs
vanillapunch.com
API / misc/camera2d

misc/camera2d

2D 카메라.

2D camera.

Camera2Dextends Object

짝Counterpart: vanilla-engine Camera2D

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

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
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());
생성자constructorconstructor()#0.3.0 부터since 0.3.0소스source

생성.

Constructor.

짝Counterpart: vanilla-engine Camera2D.new

메서드methodtick(timeDelta)#0.3.0 부터since 0.3.0소스source

갱신. (관성 이동 + 이동 트윈 + 경계 클램프)

Update. (inertial movement + move tween + bounds clamp)

timeDeltanumber
지난 프레임부터의 시간. (초)Time since the last frame. (Seconds)

짝Counterpart: vanilla-engine Camera2D.tick

메서드methodfollow(targetPositions, rate, timeDelta)#0.3.0 부터since 0.3.0소스source

대상 추적. (여러 대상이면 중점을 따라간다, 프레임 독립 지수 감쇠)

Follows targets. (follows the midpoint of multiple targets, frame-independent exponential decay)

targetPositionsVector2[]
따라갈 대상들의 월드 위치. (빈 배열이면 그대로)World positions of the targets to follow. (unchanged if the array is empty)
ratenumber
추적 속도. (클수록 빨리 붙는다)Follow speed. (larger catches up faster)
timeDeltanumber
지난 프레임부터의 시간. (초)Time since the last frame. (Seconds)

짝Counterpart: vanilla-engine Camera2D.follow

예제Example두 캐릭터의 가운데를 따라가기Follow the midpoint of two characters
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));
메서드methodpanByScreen(screenDeltaX, screenDeltaY)#0.3.0 부터since 0.3.0소스source

화면 픽셀 단위 팬. (드래그 팬, 줌과 회전을 반영해 월드 이동량으로 환산)

Pans in screen pixels. (drag pan, converted to world movement accounting for zoom and rotation)

screenDeltaXnumber
화면 가로 이동량. (픽셀, 끈 만큼 그대로 넘긴다)Horizontal screen movement. (pixels, pass the dragged amount as is)
screenDeltaYnumber
화면 세로 이동량. (픽셀, 끈 만큼 그대로 넘긴다)Vertical screen movement. (pixels, pass the dragged amount as is)

짝Counterpart: vanilla-engine Camera2D.pan_by_screen

메서드methodfling(screenVelocityX, screenVelocityY)#0.3.0 부터since 0.3.0소스source

관성 던지기. (드래그를 놓을 때 화면 픽셀 속도를 넘긴다)

Inertial fling. (pass the screen pixel velocity when releasing a drag)

screenVelocityXnumber
화면 가로 속도. (픽셀 / 초)Horizontal screen velocity. (pixels / second)
screenVelocityYnumber
화면 세로 속도. (픽셀 / 초)Vertical screen velocity. (pixels / second)

짝Counterpart: vanilla-engine Camera2D.fling

메서드methodconvertScreenDeltaToWorld(screenDeltaX, screenDeltaY)#0.4.0 부터since 0.4.0소스source

화면 픽셀 이동량 → 월드 이동량. (회전을 되돌리고 줌으로 나눈다)

Screen pixel movement → world movement. (undoes rotation and divides by zoom)

screenDeltaXnumber
화면 가로 이동량. (픽셀)Horizontal screen movement. (pixels)
screenDeltaYnumber
화면 세로 이동량. (픽셀)Vertical screen movement. (pixels)

반환ReturnsVector2 월드 이동량.World movement.

짝Counterpart: vanilla-engine Camera2D.convert_screen_delta_to_world

메서드methodzoomAt(anchorScreen, zoomFactor)#0.3.0 부터since 0.3.0소스source

화면 기준점을 고정한 줌. (휠 / 핀치, anchorScreen 아래의 월드 지점이 움직이지 않는다)

Zoom anchored at a screen point. (wheel / pinch, the world point under anchorScreen does not move)

anchorScreenVector2
화면 좌표. (뷰 좌상단 기준)Screen coordinates. (relative to the top-left of the view)
zoomFactornumber
곱할 배율. (1.1 = 10% 확대)Multiplier. (1.1 = 10% zoom in)

짝Counterpart: vanilla-engine Camera2D.zoom_at

예제Example커서 아래 지점을 붙잡은 채 확대하기Zoom in while keeping the point under the cursor fixed
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);
메서드methodtweenTo(targetPosition, targetZoom, duration = 0.4)#0.3.0 부터since 0.3.0소스source

위치 / 줌으로 이동 트윈 시작.

Starts a move tween to a position / zoom.

targetPositionVector2
옮겨 갈 월드 위치.World position to move to.
targetZoomnumber
옮겨 갈 배율. (줌 범위로 자른다)Zoom to move to. (clamped to the zoom range)
durationnumber
걸리는 시간. (초, 기본 0.4)Duration. (seconds, default 0.4)

짝Counterpart: vanilla-engine Camera2D.tween_to

예제Example0.5 초 동안 다른 자리로 옮겨 가며 확대하기Move to another spot while zooming in over 0.5 seconds
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());
메서드methodapplyTransform(graphic)#0.3.0 부터since 0.3.0소스source

그리기 변환 적용. (호출한 쪽에서 pushState / popState 로 감싼다)

Applies the drawing transform. (the caller wraps it with pushState / popState)

graphicGraphic
변환을 걸 그래픽.Graphic to apply the transform to.

짝Counterpart: vanilla-engine Camera2D.apply_transform

메서드methodbegin(graphic)#0.4.0 부터since 0.4.0소스source

그리기 시작. (상태를 쌓고 변환을 건다, deprecated/camera.js 의 begin)

Begins drawing. (pushes state and applies the transform, begin in deprecated/camera.js)

graphicGraphic
그릴 그래픽.Graphic to draw with.

짝Counterpart: vanilla-engine Camera2D.begin

메서드methodend(graphic)#0.4.0 부터since 0.4.0소스source

그리기 끝. (begin 이 쌓은 상태를 되돌린다, deprecated/camera.js 의 end)

Ends drawing. (restores the state pushed by begin, end in deprecated/camera.js)

graphicGraphic
그릴 그래픽.Graphic to draw with.

짝Counterpart: vanilla-engine Camera2D.end

메서드methodscreenToWorld(screenPosition)#0.3.0 부터since 0.3.0소스source

화면 좌표 → 월드 좌표.

Screen coordinates → world coordinates.

screenPositionVector2
화면 좌표. (뷰 좌상단 기준)Screen coordinates. (relative to the top-left of the view)

반환ReturnsVector2 월드 좌표.World coordinates.

짝Counterpart: vanilla-engine Camera2D.screen_to_world

메서드methodworldToScreen(worldPosition)#0.3.0 부터since 0.3.0소스source

월드 좌표 → 화면 좌표.

World coordinates → screen coordinates.

worldPositionVector2
월드 좌표.World coordinates.

반환ReturnsVector2 화면 좌표. (뷰 좌상단 기준)Screen coordinates. (relative to the top-left of the view)

짝Counterpart: vanilla-engine Camera2D.world_to_screen

메서드methodgetVisibleHalfExtent()#0.4.0 부터since 0.4.0소스source

화면에 보이는 월드 영역의 반 너비, 반 높이. (돌아간 뷰를 감싸는 축 정렬 상자)

Half width and half height of the world area visible on screen. (axis-aligned box enclosing the rotated view)

반환ReturnsVector2 보이는 월드 영역의 반 너비, 반 높이.Half width and half height of the visible world area.

짝Counterpart: vanilla-engine Camera2D.get_visible_half_extent

메서드methodclampToBounds()#0.3.0 부터since 0.3.0소스source

월드 경계로 클램프.

  • 보이는 영역이 경계 안에 들게 한다. 보이는 영역이 경계보다 크면(줌아웃) 축 가운데에 맞춘다.
  • 돌아가 있으면 돌아간 뷰를 감싸는 축 정렬 상자로 잰다.

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.

짝Counterpart: vanilla-engine Camera2D.clamp_to_bounds

메서드methodsetPosition(position)#0.3.0 부터since 0.3.0소스source

바라볼 월드 위치 설정. (화면 가운데, 월드 경계가 있으면 자른다)

Sets the world position to look at. (Screen center, clamped to the world bounds if any)

positionVector2
바라볼 월드 위치. (월드 경계가 있으면 자른다)World position to look at. (clamped if world bounds are set)

짝Counterpart: vanilla-engine Camera2D.set_position

메서드methodgetPosition()#0.3.0 부터since 0.3.0소스source

바라보는 월드 위치 반환. (화면 가운데)

Returns the world position being looked at. (center of the screen)

반환ReturnsVector2 바라보는 월드 위치.World position being looked at.

짝Counterpart: vanilla-engine Camera2D.get_position

메서드methodsetZoom(zoom)#0.3.0 부터since 0.3.0소스source

확대 배율 설정. (줌 범위로 자른다, 기본 1)

Sets the zoom. (clamped to the zoom range, default 1)

zoomnumber
확대 배율.Zoom factor.

짝Counterpart: vanilla-engine Camera2D.set_zoom

메서드methodgetZoom()#0.3.0 부터since 0.3.0소스source

확대 배율 반환.

Returns the zoom.

반환Returnsnumber 확대 배율.Zoom factor.

짝Counterpart: vanilla-engine Camera2D.get_zoom

메서드methodsetRotation(rotation)#0.4.0 부터since 0.4.0소스source

회전 각도 설정.

Sets the rotation angle.

rotationnumber
도. (화면 가운데를 축으로 돈다)Degrees. (rotates around the screen center)

짝Counterpart: vanilla-engine Camera2D.set_rotation

메서드methodgetRotation()#0.4.0 부터since 0.4.0소스source

회전 각도 반환. (도)

Returns the rotation angle. (degrees)

반환Returnsnumber 회전 각도. (도)Rotation angle. (degrees)

짝Counterpart: vanilla-engine Camera2D.get_rotation

메서드methodsetViewSize(viewSize)#0.3.0 부터since 0.3.0소스source

화면 크기 설정. (화면 가운데를 잡는 데 쓴다, 기본 960 x 640)

Sets the screen size. (used to find the screen center, default 960 x 640)

viewSizeVector2
화면 크기. (픽셀)Screen size. (pixels)

짝Counterpart: vanilla-engine Camera2D.set_view_size

메서드methodgetViewSize()#0.3.0 부터since 0.3.0소스source

화면 크기 반환.

Returns the screen size.

반환ReturnsVector2 화면 크기. (픽셀)Screen size. (pixels)

짝Counterpart: vanilla-engine Camera2D.get_view_size

메서드methodsetWorldBounds(worldBounds)#0.3.0 부터since 0.3.0소스source

월드 경계 설정. (보이는 영역이 이 안에 들게 자른다)

Sets the world bounds. (clamps so the visible area stays inside)

worldBoundsRect | null
월드 경계. (null 이면 자르지 않는다)World bounds. (no clamping if null)

짝Counterpart: vanilla-engine Camera2D.set_world_bounds

메서드methodgetWorldBounds()#0.3.0 부터since 0.3.0소스source

월드 경계 반환.

Returns the world bounds.

반환ReturnsRect | null 월드 경계. (없으면 null)World bounds. (null if none)

짝Counterpart: vanilla-engine Camera2D.get_world_bounds

메서드methodsetZoomRange(minZoom, maxZoom)#0.3.0 부터since 0.3.0소스source

줌 범위 설정. (지금 배율도 이 범위로 자른다, 기본 0.1 ~ 8)

Sets the zoom range. (also clamps the current zoom to this range, default 0.1 ~ 8)

minZoomnumber
최소 배율.Minimum zoom.
maxZoomnumber
최대 배율.Maximum zoom.

짝Counterpart: vanilla-engine Camera2D.set_zoom_range

메서드methodsetInertiaDamping(inertiaDamping)#0.3.0 부터since 0.3.0소스source

관성 감쇠 설정. (클수록 빨리 멈춘다, 기본 6)

Sets the inertia damping. (larger stops sooner, default 6)

inertiaDampingnumber
관성 감쇠. (초당 지수 감쇠 계수)Inertia damping. (exponential decay coefficient per second)

짝Counterpart: vanilla-engine Camera2D.set_inertia_damping

메서드methodisTweening()#0.3.0 부터since 0.3.0소스source

이동 트윈 중인지 여부.

Whether a move tween is running.

반환Returnsboolean 이동 트윈 중이면 참.True while a move tween is running.

짝Counterpart: vanilla-engine Camera2D.is_tweening

메서드methodstopInertia()#0.3.0 부터since 0.3.0소스source

관성 정지.

Stops inertia.

짝Counterpart: vanilla-engine Camera2D.stop_inertia