vanilladocs
vanillapunch.com
API / misc/camera2d

misc/camera2d

2D 카메라.

  • 원본 misc/camera2d.js 를 옮긴 것이다. 추적, 월드 경계 클램프, 드래그 팬, 커서 고정 줌, 관성, 이동 트윈을 한 곳에 모았다.
  • position 은 카메라가 바라보는 월드 좌표(화면 가운데), zoom 은 확대 배율, rotation 은 화면 가운데를 축으로 도는 각도(도)다. rotation 만큼 월드가 화면에서 돈다. (원본 deprecated/camera.js 의 begin 이 scale 뒤 rotate 를 거는 것과 같은 방향)
  • 원본처럼 컴포넌트가 아니라 그냥 값이다. 들고 있는 쪽(씬 등)이 tick 을 부르고, 월드를 그리기 전에 apply_transform 을 건다.
  • 사용:
camera.set_view_size(view_size);                    // 매 프레임 또는 리사이즈 시
camera.follow(&[hero_position], 6.0, time_delta);  // 추적 (선택)
camera.tick(time_delta);
camera.begin(graphic); ...월드 렌더... camera.end(graphic);   // push_state + apply_transform / pop_state
  • 원본과 다른 점: 이름을 줄이지 않는 규칙에 따라 minZoom / maxZoom 을 minimum_zoom / maximum_zoom 으로 쓴다. (set_zoom_range 의 뜻은 같다) tween_to 의 기본 길이 0.4 초는 DEFAULT_TWEEN_DURATION 상수로 넘긴다. (러스트는 기본 인자가 없다)

2D camera.

  • A port of the original misc/camera2d.js. Gathers following, world bounds clamping, drag panning, cursor-anchored zoom, inertia, and movement tweens in one place.
  • position is the world coordinate the camera looks at (screen center), zoom is the magnification, and rotation is the angle (degrees) around the screen center. The world rotates on screen by rotation. (same direction as the original deprecated/camera.js begin applying rotate after scale)
  • Unlike the original, it is a plain value, not a component. The owner (a scene, etc.) calls tick and applies apply_transform before drawing the world.
  • Usage:
camera.set_view_size(view_size);                    // every frame or on resize
camera.follow(&[hero_position], 6.0, time_delta);  // follow (optional)
camera.tick(time_delta);
camera.begin(graphic); ...render world... camera.end(graphic);   // push_state + apply_transform / pop_state
  • Differences from the original:
Following the no-abbreviation naming rule, minZoom / maxZoom are written as minimum_zoom / maximum_zoom. (set_zoom_range means the same)
The default tween_to duration of 0.4 seconds is passed as the DEFAULT_TWEEN_DURATION constant. (Rust has no default arguments)
예제Example주인공을 따라가며 월드 그리기Draw the world while following the hero
use vanilla::{Camera2D, Colors, Graphic, Rect, Vector2};

fn draw_world(camera: &mut Camera2D, graphic: &mut Graphic, view_size: Vector2, hero_position: Vector2, time_delta: f64) {
	camera.set_view_size(view_size);
	camera.follow(&[hero_position], 6.0, time_delta);
	camera.tick(time_delta);
	camera.begin(graphic);
	graphic.set_fill_color(Colors::WHITE);
	graphic.draw_rect(Rect::create(hero_position.x - 16.0, hero_position.y - 16.0, 32.0, 32.0));
	camera.end(graphic);
}

Camera2Dstruct traits Clone, Debug, Default

짝Counterpart: vanilla.js Camera2D소스source

2D 카메라.

  • 위치(화면 가운데가 보는 월드 좌표), 배율, 회전(도), 뷰 크기(픽셀)로 화면과 월드 좌표를 오간다.

2D camera.

  • Converts between screen and world coordinates using position (the world coordinate seen at the screen center), zoom, rotation (degrees), and view size (pixels).
예제Example화면 좌표와 월드 좌표 오가기Convert between screen and world coordinates
use vanilla::{Camera2D, Vector2};

let mut camera = Camera2D::new();
camera.set_view_size(Vector2::create(800.0, 600.0));
camera.set_position(Vector2::create(100.0, 50.0));
camera.set_zoom(2.0);
let screen_position = camera.world_to_screen(Vector2::create(110.0, 50.0));
assert_eq!(screen_position, Vector2::create(420.0, 300.0));
assert_eq!(camera.screen_to_world(screen_position), Vector2::create(110.0, 50.0));
예제Example월드 경계 안에 보이는 영역 가두기Keep the visible area inside the world bounds
use vanilla::{Camera2D, Rect, Vector2};

let mut camera = Camera2D::new();
camera.set_view_size(Vector2::create(400.0, 300.0));
camera.set_world_bounds(Some(Rect::create(0.0, 0.0, 1000.0, 1000.0)));
camera.set_position(Vector2::create(-500.0, 2000.0));
assert_eq!(camera.get_position(), Vector2::create(200.0, 850.0));
생성자constructorpub fn new() -> Camera2D#0.3.2 부터since 0.3.2소스source

생성. (위치 0, 배율 1, 회전 0, 뷰 960x640, 경계 없음, 관성 감쇠 6, 배율 범위 0.1 ~ 8)

Constructor. (position 0, zoom 1, rotation 0, view 960x640, no bounds, inertia damping 6, zoom range 0.1 ~ 8)

반환ReturnsCamera2D 기본값으로 채운 카메라.A camera filled with default values.

짝Counterpart: vanilla.js Camera2D.constructor

정적staticpub const DEFAULT_TWEEN_DURATION: f64 = 0.4#0.3.2 부터since 0.3.2소스source

tween_to 의 기본 길이. (초, 원본 duration = 0.4)

Default duration of tween_to. (seconds, original duration = 0.4)

반환Returnsf64

메서드methodpub fn tick(&mut self, time_delta: f64)#0.3.2 부터since 0.3.2소스source

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

  • 관성 속도는 e^(-관성 감쇠 * time_delta) 배로 줄고, 두 축 모두 1 아래로 떨어지면 0 이 된다.
  • 트윈은 3 차 감속(ease out cubic)으로 위치를 잇고 배율은 등비로 잇는다. 길이를 다 채운 프레임에 끝난다.

Update. (in order: inertia movement, movement tween, bounds clamp)

  • The inertia velocity is multiplied by e^(-inertia damping * time_delta), and becomes 0 once both axes drop below 1.
  • The tween interpolates the position with a cubic ease out and the zoom geometrically. It ends on the frame that fills the duration.
time_deltaf64
지난 프레임부터 흐른 시간. (초)Time elapsed since the last frame. (seconds)

짝Counterpart: vanilla.js Camera2D.tick

메서드methodpub fn follow(&mut self, target_positions: &[Vector2], rate: f64, time_delta: f64)#0.3.2 부터since 0.3.2소스source

대상 추적. (여러 대상이면 중점을 따라간다. 프레임 독립 지수 감쇠, rate 가 클수록 빨리 붙는다)

  • 한 번에 남은 거리의 1 - e^(-rate * time_delta) 만큼 다가간다. 경계 클램프는 하지 않는다. (tick 에서)

Follows targets. (follows the midpoint when there are several, frame-independent exponential decay, the larger rate is the faster it catches up)

  • Each call closes 1 - e^(-rate * time_delta) of the remaining distance. Does not clamp to bounds. (tick does)
target_positions&[Vector2]
따라갈 월드 좌표 목록. 비어 있으면 아무것도 하지 않는다.List of world coordinates to follow. Does nothing if empty.
ratef64
다가가는 빠르기. (초당 지수 감쇠율, 원본 사용 예 6)Approach speed. (exponential decay rate per second, the original usage example uses 6)
time_deltaf64
지난 프레임부터 흐른 시간. (초)Time elapsed since the last frame. (seconds)

짝Counterpart: vanilla.js Camera2D.follow

예제Example두 대상의 중점으로 붙기Stick to the midpoint of two targets
use vanilla::{Camera2D, Vector2};

let mut camera = Camera2D::new();
let target_positions = [Vector2::create(100.0, 0.0), Vector2::create(300.0, 200.0)];
for _ in 0..600 {
	camera.follow(&target_positions, 6.0, 1.0 / 60.0);
}
let position = camera.get_position();
assert!((position.x - 200.0).abs() < 0.01);
assert!((position.y - 100.0).abs() < 0.01);
메서드methodpub fn pan_by_screen(&mut self, screen_delta_x: f64, screen_delta_y: f64)#0.3.2 부터since 0.3.2소스source

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

  • 끈 쪽으로 월드가 따라오게 카메라는 반대로 움직인다. 경계로 클램프한다.

Pans by screen pixels. (drag panning, converted to a world offset taking zoom and rotation into account)

  • The camera moves the opposite way so the world follows the drag. Clamps to bounds.
screen_delta_xf64
화면에서 끈 가로 이동량. (픽셀)Horizontal distance dragged on screen. (pixels)
screen_delta_yf64
화면에서 끈 세로 이동량. (픽셀)Vertical distance dragged on screen. (pixels)

짝Counterpart: vanilla.js Camera2D.panByScreen

예제Example2 배로 확대한 화면을 오른쪽으로 40 픽셀 끌기Drag a 2x zoomed view 40 pixels to the right
use vanilla::{Camera2D, Vector2};

let mut camera = Camera2D::new();
camera.set_zoom(2.0);
camera.pan_by_screen(40.0, 0.0);
assert_eq!(camera.get_position(), Vector2::create(-20.0, 0.0));
메서드methodpub fn fling(&mut self, screen_velocity_x: f64, screen_velocity_y: f64)#0.3.2 부터since 0.3.2소스source

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

  • pan_by_screen 과 같은 방향의 월드 속도로 바꿔 두고, tick 이 그 속도로 옮기며 줄인다.

Flings with inertia. (pass the screen pixel velocity when the drag is released)

  • Converts it to a world velocity in the same direction as pan_by_screen, and tick moves by that velocity while slowing it down.
screen_velocity_xf64
화면 가로 속도. (초당 픽셀)Horizontal screen velocity. (pixels per second)
screen_velocity_yf64
화면 세로 속도. (초당 픽셀)Vertical screen velocity. (pixels per second)

짝Counterpart: vanilla.js Camera2D.fling

예제Example오른쪽으로 던지면 카메라는 왼쪽으로 미끄러진다Fling to the right and the camera slides to the left
use vanilla::Camera2D;

let mut camera = Camera2D::new();
camera.fling(600.0, 0.0);
camera.tick(0.1);
assert!(camera.get_position().x < 0.0);
메서드methodpub fn convert_screen_delta_to_world(&self, screen_delta_x: f64, screen_delta_y: f64) -> Vector2#0.4.0 부터since 0.4.0소스source

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

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

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

반환ReturnsVector2 같은 이동을 월드 좌표로 잰 양. (위치는 더하지 않는다)The same movement measured in world coordinates. (not added to the position)

짝Counterpart: vanilla.js Camera2D.convertScreenDeltaToWorld

메서드methodpub fn zoom_at(&mut self, anchor_screen: Vector2, zoom_factor: f64)#0.3.2 부터since 0.3.2소스source

화면 기준점을 고정한 줌. (휠 / 핀치. anchor_screen 아래의 월드 지점이 움직이지 않는다, 1.1 = 10% 확대)

  • 새 배율은 배율 범위로 자른다. 잘라서 배율이 그대로면 아무것도 하지 않는다. 바꾼 뒤 경계로 클램프한다.

Zooms with a fixed screen anchor. (wheel / pinch, the world point under anchor_screen does not move, 1.1 = 10% zoom in)

  • The new zoom is clamped to the zoom range. Does nothing if the clamped zoom is unchanged. Clamps to bounds after the change.
anchor_screenVector2
고정할 화면 좌표. (픽셀, 보통 커서나 두 손가락의 가운데)Screen coordinate to keep fixed. (pixels, usually the cursor or the midpoint of two fingers)
zoom_factorf64
지금 배율에 곱할 값. (1 보다 크면 확대, 작으면 축소)Value to multiply the current zoom by. (greater than 1 zooms in, less zooms out)

짝Counterpart: vanilla.js Camera2D.zoomAt

예제Example커서 아래 지점을 고정하고 2 배 확대Zoom in 2x keeping the point under the cursor fixed
use vanilla::{Camera2D, Vector2};

let mut camera = Camera2D::new();
camera.set_view_size(Vector2::create(800.0, 600.0));
let anchor_screen = Vector2::create(600.0, 300.0);
let anchor_world = camera.screen_to_world(anchor_screen);
camera.zoom_at(anchor_screen, 2.0);
assert_eq!(camera.get_zoom(), 2.0);
assert_eq!(camera.screen_to_world(anchor_screen), anchor_world);
메서드methodpub fn tween_to(&mut self, target_position: Vector2, target_zoom: f64, duration: f64)#0.3.2 부터since 0.3.2소스source

위치 / 줌으로 이동 트윈 시작. (관성은 멈춘다. 기본 길이는 DEFAULT_TWEEN_DURATION)

  • 진행은 tick 이 맡는다. 이미 트윈 중이면 지금 자리에서 새로 시작한다.

Starts a movement tween to a position / zoom. (stops inertia, default duration is DEFAULT_TWEEN_DURATION)

  • tick drives the progress. If already tweening, starts anew from the current spot.
target_positionVector2
도착할 월드 좌표.Destination world coordinate.
target_zoomf64
도착할 배율. (배율 범위로 자른다)Destination zoom. (clamped to the zoom range)
durationf64
걸릴 시간. (초, 0.0001 보다 작으면 0.0001)Duration. (seconds, 0.0001 if less than 0.0001)

짝Counterpart: vanilla.js Camera2D.tweenTo

예제Example0.4 초 동안 옮기며 2 배로 확대Move over 0.4 seconds while zooming in 2x
use vanilla::{Camera2D, Vector2};

let mut camera = Camera2D::new();
camera.tween_to(Vector2::create(300.0, 0.0), 2.0, Camera2D::DEFAULT_TWEEN_DURATION);
assert!(camera.is_tweening());
for _ in 0..30 {
	camera.tick(1.0 / 60.0);
}
assert!(!camera.is_tweening());
assert!((camera.get_position().x - 300.0).abs() < 0.001);
assert!((camera.get_zoom() - 2.0).abs() < 0.001);
메서드methodpub fn apply_transform(&self, graphic: &mut Graphic)#0.3.2 부터since 0.3.2소스source

그리기 변환 적용. (부른 쪽에서 push_state / pop_state 로 감싼다)

  • 뷰 가운데로 옮기고, 배율, 회전, 위치를 거꾸로 옮기는 차례로 지금 변환에 곱한다.

Applies the drawing transform. (the caller wraps it with push_state / pop_state)

  • Multiplies into the current transform in order: translate to the view center, zoom, rotation, then translate by the negated position.
graphic&mut Graphic
변환을 걸 그래픽.Graphic to apply the transform to.

짝Counterpart: vanilla.js Camera2D.applyTransform

메서드methodpub fn begin(&self, graphic: &mut Graphic)#0.4.0 부터since 0.4.0소스source

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

  • 월드를 다 그린 뒤 end 를 짝으로 부른다.

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

  • Call end as its pair after drawing the whole world.
graphic&mut Graphic
그릴 그래픽.Graphic to draw with.

짝Counterpart: vanilla.js Camera2D.begin

메서드methodpub fn end(&self, graphic: &mut Graphic)#0.4.0 부터since 0.4.0소스source

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

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

graphic&mut Graphic
begin 에 넘긴 그래픽.The graphic passed to begin.

짝Counterpart: vanilla.js Camera2D.end

메서드methodpub fn screen_to_world(&self, screen_position: Vector2) -> Vector2#0.3.2 부터since 0.3.2소스source

화면 좌표 → 월드 좌표.

Screen coordinates → world coordinates.

screen_positionVector2
화면 좌표. (픽셀, 뷰 왼쪽 위 기준)Screen coordinate. (pixels, relative to the top left of the view)

반환ReturnsVector2 그 화면 지점에 보이는 월드 좌표.The world coordinate seen at that screen point.

짝Counterpart: vanilla.js Camera2D.screenToWorld

메서드methodpub fn world_to_screen(&self, world_position: Vector2) -> Vector2#0.3.2 부터since 0.3.2소스source

월드 좌표 → 화면 좌표.

World coordinates → screen coordinates.

world_positionVector2
월드 좌표.World coordinates.

반환ReturnsVector2 그 월드 지점이 보이는 화면 좌표. (픽셀, 뷰 왼쪽 위 기준, 화면 밖일 수 있다)The screen coordinate where that world point appears. (pixels, relative to the top left of the view, may be off screen)

짝Counterpart: vanilla.js Camera2D.worldToScreen

메서드methodpub fn get_visible_half_extent(&self) -> Vector2#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 x 는 반 너비, y 는 반 높이. (월드 단위)x is the half width, y is the half height. (world units)

짝Counterpart: vanilla.js Camera2D.getVisibleHalfExtent

메서드methodpub fn clamp_to_bounds(&mut self)#0.3.2 부터since 0.3.2소스source

월드 경계로 클램프. (보이는 영역이 경계 안에 들게 한다. 보이는 영역이 경계보다 크면(줌아웃) 그 축은 가운데에 맞춘다)

  • 돌아가 있으면 돌아간 뷰를 감싸는 축 정렬 상자로 잰다.

Clamps to the world bounds. (keeps the visible area inside the bounds, and centers an axis when the visible area is larger than the bounds (zoomed out))

  • When rotated, measures with the axis-aligned box that encloses the rotated view.

짝Counterpart: vanilla.js Camera2D.clampToBounds

메서드methodpub fn set_position(&mut self, position: Vector2)#0.3.2 부터since 0.3.2소스source

위치 설정. (경계로 클램프한다)

Sets the position. (clamps to bounds)

positionVector2
화면 가운데에 둘 월드 좌표.World coordinate to place at the screen center.

짝Counterpart: vanilla.js Camera2D.setPosition

메서드methodpub fn get_position(&self) -> Vector2#0.3.2 부터since 0.3.2소스source

위치 반환.

Returns the position.

반환ReturnsVector2 화면 가운데가 보는 월드 좌표.The world coordinate seen at the screen center.

짝Counterpart: vanilla.js Camera2D.getPosition

메서드methodpub fn set_zoom(&mut self, zoom: f64)#0.3.2 부터since 0.3.2소스source

배율 설정. (배율 범위로 자르고 경계로 클램프한다)

Sets the zoom. (clamped to the zoom range and to bounds)

zoomf64
확대 배율. (1 이 원래 크기)Magnification. (1 is the original size)

짝Counterpart: vanilla.js Camera2D.setZoom

메서드methodpub fn get_zoom(&self) -> f64#0.3.2 부터since 0.3.2소스source

배율 반환.

Returns the scale.

반환Returnsf64 확대 배율.Zoom factor.

짝Counterpart: vanilla.js Camera2D.getZoom

메서드methodpub fn set_rotation(&mut self, rotation: f64)#0.4.0 부터since 0.4.0소스source

회전 설정. (도, 화면 가운데를 축으로 돈다. 경계로 클램프한다)

Sets the rotation. (degrees, rotates around the screen center, clamps to bounds)

rotationf64
회전 각도. (도, 범위로 자르지 않는다)Rotation angle. (degrees, not clamped to a range)

짝Counterpart: vanilla.js Camera2D.setRotation

메서드methodpub fn get_rotation(&self) -> f64#0.4.0 부터since 0.4.0소스source

회전 반환. (도)

Returns the rotation. (degrees)

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

짝Counterpart: vanilla.js Camera2D.getRotation

메서드methodpub fn set_view_size(&mut self, view_size: Vector2)#0.3.2 부터since 0.3.2소스source

뷰 크기 설정. (화면 가운데를 정하는 크기)

  • 경계 클램프는 다음 tick 이나 다른 설정 때 한다.

Sets the view size. (the size that defines the screen center)

  • The bounds clamp happens on the next tick or another setter.
view_sizeVector2
뷰 너비와 높이. (픽셀)View width and height. (pixels)

짝Counterpart: vanilla.js Camera2D.setViewSize

메서드methodpub fn get_view_size(&self) -> Vector2#0.3.2 부터since 0.3.2소스source

뷰 크기 반환.

Returns the view size.

반환ReturnsVector2 뷰 너비와 높이. (픽셀)View width and height. (pixels)

짝Counterpart: vanilla.js Camera2D.getViewSize

메서드methodpub fn set_world_bounds(&mut self, world_bounds: Option<Rect>)#0.3.2 부터since 0.3.2소스source

월드 경계 설정. (None 이면 경계 없음)

Sets the world bounds. (None means no bounds)

world_boundsOption<Rect>
보이는 영역을 가둘 월드 사각형. None 이면 경계 없음. (바로 클램프한다)World rectangle to keep the visible area in. None means no bounds. (clamps immediately)

짝Counterpart: vanilla.js Camera2D.setWorldBounds

메서드methodpub fn get_world_bounds(&self) -> Option<Rect>#0.3.2 부터since 0.3.2소스source

월드 경계 반환.

Returns the world bounds.

반환ReturnsOption<Rect> 월드 경계. 경계가 없으면 None.World bounds. None if there are no bounds.

짝Counterpart: vanilla.js Camera2D.getWorldBounds

메서드methodpub fn set_zoom_range(&mut self, minimum_zoom: f64, maximum_zoom: f64)#0.3.2 부터since 0.3.2소스source

배율 범위 설정. (지금 배율도 새 범위로 다시 자른다)

Sets the zoom range. (the current zoom is clamped again to the new range)

minimum_zoomf64
가장 작은 배율. (기본 0.1)Smallest zoom. (default 0.1)
maximum_zoomf64
가장 큰 배율. (기본 8)Largest zoom. (default 8)

짝Counterpart: vanilla.js Camera2D.setZoomRange

메서드methodpub fn set_inertia_damping(&mut self, inertia_damping: f64)#0.3.2 부터since 0.3.2소스source

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

Sets the inertia damping. (the larger, the faster it stops)

inertia_dampingf64
초당 지수 감쇠율. (기본 6, tick 마다 속도에 e^(-inertia_damping * time_delta) 를 곱한다)Exponential decay rate per second. (default 6, each tick multiplies the velocity by e^(-inertia_damping * time_delta))

짝Counterpart: vanilla.js Camera2D.setInertiaDamping

메서드methodpub fn is_tweening(&self) -> bool#0.3.2 부터since 0.3.2소스source

이동 트윈 중인지.

Whether a movement tween is running.

반환Returnsbool tween_to 로 시작한 트윈이 아직 끝나지 않았으면 true.true if the tween started by tween_to has not finished yet.

짝Counterpart: vanilla.js Camera2D.isTweening

메서드methodpub fn stop_inertia(&mut self)#0.3.2 부터since 0.3.2소스source

관성 정지.

Stops inertia.

짝Counterpart: vanilla.js Camera2D.stopInertia