vanilladocs
vanillapunch.com
API / misc/typewriter

misc/typewriter

타자기 연출기.

  • 원본 misc/typewriter.js 를 옮긴 것이다. Text 처럼 보일 글자 수를 정할 수 있는 대상의 글자를 초당 정한 속도로 한 자씩 드러낸다. (비주얼노벨 / RPG 대사 연출)
  • 사용:
let mut typewriter = Typewriter::new(TypewriterOptions { characters_per_second: 30.0, ..TypewriterOptions::default() });
let label = node_tree[label_id].get_component_mut::<Text>().unwrap();
typewriter.start(label, Some("안녕하세요. 모험을 시작합니다."));
// 매 프레임: typewriter.tick(label, time_delta);
// 입력에서: 끝났으면(typewriter.is_finished()) 다음 대사로, 아니면 typewriter.skip_to_end(label)
  • 원본과 다른 점: 원본은 대상을 생성자에서 받아 들고 있는다. 러스트 판은 노드 안의 컴포넌트를 들고 있을 수 없어서 start / tick / skip_to_end 때마다 대상(&mut dyn TypewriterTarget)을 넘긴다. Text 는 TypewriterTarget 을 구현한다. 글자 수는 원본처럼 글자 묶음(받침, 결합 부호, 이모지 묶음을 한 자로) 단위로 센다. 글자 공개 알림은 (글자 묶음, 번호) 를 받는다. options 객체는 TypewriterOptions 구조체다.

Typewriter effect.

  • A port of the original misc/typewriter.js. Reveals the text of a target that can set its visible character count, like Text, one character at a time at a set speed per second. (visual novel / RPG dialogue presentation)
  • Usage:
let mut typewriter = Typewriter::new(TypewriterOptions { characters_per_second: 30.0, ..TypewriterOptions::default() });
let label = node_tree[label_id].get_component_mut::<Text>().unwrap();
typewriter.start(label, Some("Hello. The adventure begins."));
// every frame: typewriter.tick(label, time_delta);
// on input: next line if finished (typewriter.is_finished()), otherwise typewriter.skip_to_end(label)
  • Differences from the original: The original takes the target in the constructor and holds it. The Rust version cannot hold a component inside a node, so the target (&mut dyn TypewriterTarget) is passed on every start / tick / skip_to_end. Text implements TypewriterTarget. As in the original, characters are counted in grapheme clusters (final consonants, combining marks, and emoji sequences count as one). The character reveal notification receives (grapheme cluster, index). The options object is the TypewriterOptions struct.

TypewriterTargettrait

소스source

타자기 대상. (글 설정, 글 반환, 보일 글자 수 설정. -1 이면 전체)

  • Text 가 구현한다. 다른 글 그리기도 이것을 구현하면 Typewriter 로 드러낼 수 있다.

Typewriter target. (set text, return text, set visible character count. -1 means all)

  • Implemented by Text. Other text renderers can be revealed by Typewriter if they implement this.
예제Example보일 글자 수만 기억하는 대상A target that only remembers the visible character count
use vanilla::{Typewriter, TypewriterOptions, TypewriterTarget};

struct CountingLabel {
	text: String,
	visible_character_count: i32,
}

impl TypewriterTarget for CountingLabel {
	fn set_text(&mut self, text: &str) {
		self.text = text.to_string();
	}

	fn get_text(&self) -> &str {
		&self.text
	}

	fn set_visible_character_count(&mut self, visible_character_count: i32) {
		self.visible_character_count = visible_character_count;
	}
}

let mut label = CountingLabel {
	text: String::new(),
	visible_character_count: -1,
};
let mut typewriter = Typewriter::new(TypewriterOptions {
	characters_per_second: 10.0,
	..TypewriterOptions::default()
});
typewriter.start(&mut label, Some("hello"));
typewriter.tick(&mut label, 0.25);
assert_eq!(label.visible_character_count, 2);
메서드methodfn set_text(&mut self, text: &str)#0.3.2 부터since 0.3.2소스source

글 설정.

Sets the text.

text&str
새 글.New text.
메서드methodfn get_text(&self) -> &str#0.3.2 부터since 0.3.2소스source

글 반환.

Returns the text.

반환Returns&str 지금 글 전체. (보일 글자 수와 상관없다)The current full text. (regardless of the visible character count)

메서드methodfn set_visible_character_count(&mut self, visible_character_count: i32)#0.3.2 부터since 0.3.2소스source

보일 글자 수 설정. (-1 이면 전체)

Sets the visible character count. (-1 means all)

visible_character_counti32
앞에서부터 보일 글자 묶음 수. (-1 이면 전체)Number of grapheme clusters visible from the start. (-1 means all)

TypewriterOptionsstruct traits Clone, Copy, Debug, PartialEq, Default

소스source

타자기 설정. (원본 options = { characters_per_second = 30, fast_forward_multiplier = 8 })

Typewriter settings. (original options = { characters_per_second = 30, fast_forward_multiplier = 8 })

예제Example속도만 바꾸기Change only the speed
use vanilla::{Typewriter, TypewriterOptions};

let typewriter_options = TypewriterOptions {
	characters_per_second: 20.0,
	..TypewriterOptions::default()
};
assert_eq!(typewriter_options.fast_forward_multiplier, 8.0);
let typewriter = Typewriter::new(typewriter_options);
assert!(typewriter.is_finished());
필드fieldpub characters_per_second: f64#0.3.2 부터since 0.3.2소스source

초당 글자 수.

Characters per second.

반환Returnsf64

필드fieldpub fast_forward_multiplier: f64#0.3.2 부터since 0.3.2소스source

빨리 감기일 때 곱하는 배율.

Multiplier applied when fast forwarding.

반환Returnsf64

Typewriterstruct traits Default

짝Counterpart: vanilla.js Typewriter소스source

타자기 연출기.

  • start 로 대상과 글을 넘기고, 매 프레임 tick 에 같은 대상을 넘긴다. 입력이 오면 끝났으면 다음 대사로, 아니면 skip_to_end.

Typewriter effect.

  • Pass the target and text with start, and pass the same target to tick every frame. On input, go to the next line if finished, otherwise skip_to_end.
예제Example노드의 Text 에 대사 드러내기Reveal a line in a node's Text
use vanilla::{NodeTree, Text, Typewriter, TypewriterOptions};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let label_id = node_tree.create_child(root_id, "label");
node_tree[label_id].add_component(Text::new());

let mut typewriter = Typewriter::new(TypewriterOptions {
	characters_per_second: 30.0,
	..TypewriterOptions::default()
});
let label = node_tree[label_id].get_component_mut::<Text>().unwrap();
typewriter.start(label, Some("Hello. The adventure begins."));
typewriter.tick(label, 0.1);
assert_eq!(label.get_visible_character_count(), 3);

if typewriter.is_finished() {
	typewriter.start(label, Some("Next line."));
}
else {
	typewriter.skip_to_end(label);
}
assert!(typewriter.is_finished());
assert_eq!(label.get_visible_character_count(), -1);
생성자constructorpub fn new(options: TypewriterOptions) -> Typewriter#0.3.2 부터since 0.3.2소스source

생성. (처음에는 끝난 상태)

Constructor. (finished state initially)

optionsTypewriterOptions
초당 글자 수와 빨리 감기 배율.Characters per second and fast forward multiplier.

반환ReturnsTypewriter 글이 없고 끝난 상태인 새 타자기.A new typewriter with no text, in the finished state.

짝Counterpart: vanilla.js Typewriter.constructor

메서드methodpub fn start(&mut self, target: &mut dyn TypewriterTarget, text: Option<&str>)#0.3.2 부터since 0.3.2소스source

시작. (text 를 넘기면 대상의 글도 바꾼다. 없으면 대상의 지금 글을 쓴다. 빈 글이면 바로 끝난 상태)

  • 대상의 보일 글자 수를 0 으로 하고 빨리 감기를 끈다. 빈 글이면 -1(전체)로 둔다. 완료 알림은 부르지 않는다.

Starts. (if text is passed, also changes the target's text. Otherwise uses the target's current text. An empty text is immediately finished)

  • Sets the target's visible character count to 0 and turns fast forward off. For an empty text, leaves it at -1 (all). The completion notification is not called.
target&mut dyn TypewriterTarget
글을 드러낼 대상.Target to reveal the text in.
textOption<&str>
새로 넣을 글. None 이면 대상의 지금 글.New text to put in. None uses the target's current text.

짝Counterpart: vanilla.js Typewriter.start

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

갱신. (쌓인 만큼 글자를 드러내고, 새로 드러난 글자마다 알린다. 다 드러나면 끝낸다)

  • 끝난 뒤에는 아무것도 하지 않는다. 다 드러나면 보일 글자 수를 -1 로 하고 완료를 알린다.

Update. (reveals as many characters as accumulated and notifies for each newly revealed character. Finishes when everything is revealed)

  • Does nothing after finishing. When everything is revealed, sets the visible character count to -1 and notifies completion.
target&mut dyn TypewriterTarget
start 에 넘긴 대상.The target passed to start.
time_deltaf64
지난 시간. (초, 초당 글자 수 * 배율 * time_delta 만큼 쌓는다)Elapsed time. (seconds, accumulates characters per second * multiplier * time_delta)

짝Counterpart: vanilla.js Typewriter.tick

예제Example드러난 글자마다 알림 받기Get a notification for each revealed character
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Text, Typewriter, TypewriterOptions};

let revealed_list = Rc::new(RefCell::new(Vec::new()));
let revealed_list_for_event = revealed_list.clone();
let mut label = Text::new();
let mut typewriter = Typewriter::new(TypewriterOptions {
	characters_per_second: 10.0,
	..TypewriterOptions::default()
});
typewriter.set_character_revealed_event(move |character, character_index| {
	revealed_list_for_event.borrow_mut().push((character.to_string(), character_index));
});
typewriter.start(&mut label, Some("abc"));
typewriter.tick(&mut label, 0.25);
assert_eq!(*revealed_list.borrow(), vec![(String::from("a"), 0), (String::from("b"), 1)]);
메서드methodpub fn skip_to_end(&mut self, target: &mut dyn TypewriterTarget)#0.3.2 부터since 0.3.2소스source

곧바로 끝까지 드러내기. (드러나지 않은 글자의 공개 알림은 부르지 않는다)

  • 끝난 상태면 아무것도 하지 않는다. 아니면 보일 글자 수를 -1 로 하고 완료를 알린다.

Reveals everything immediately. (reveal notifications for unrevealed characters are not called)

  • Does nothing if finished. Otherwise sets the visible character count to -1 and notifies completion.
target&mut dyn TypewriterTarget
start 에 넘긴 대상.The target passed to start.

짝Counterpart: vanilla.js Typewriter.skipToEnd

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

끝났는지.

Whether it has finished.

반환Returnsbool 글을 다 드러냈거나 아직 start 하지 않았으면 true.true if all the text has been revealed or start has not been called yet.

짝Counterpart: vanilla.js Typewriter.isFinished

메서드methodpub fn set_fast_forward(&mut self, is_fast_forward: bool)#0.3.2 부터since 0.3.2소스source

빨리 감기 설정. (누르고 있는 동안 등)

Sets fast-forward. (while held, etc.)

is_fast_forwardbool
true 면 속도에 빨리 감기 배율을 곱한다. (start 하면 false 로 돌아간다)If true, multiplies the speed by the fast forward multiplier. (returns to false on start)

짝Counterpart: vanilla.js Typewriter.setFastForward

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

속도 설정. (초당 글자 수)

Sets the speed. (characters per second)

characters_per_secondf64
초당 드러낼 글자 묶음 수.Number of grapheme clusters revealed per second.

짝Counterpart: vanilla.js Typewriter.setCharactersPerSecond

메서드methodpub fn set_character_revealed_event(&mut self, character_revealed_event: impl FnMut(&str, usize) + 'static)#0.3.2 부터since 0.3.2소스source

글자 공개 알림 설정. (글자, 번호)

Sets the character reveal notification. (character, index)

character_revealed_eventimpl FnMut(&str, usize) + 'static
글자가 드러날 때마다 부를 함수. 그 글자 묶음과 0 부터 센 번호를 받는다.Function to call each time a character is revealed. Receives that grapheme cluster and its index counted from 0.

짝Counterpart: vanilla.js Typewriter.setCharacterRevealedEvent

메서드methodpub fn set_complete_event(&mut self, complete_event: impl FnMut() + 'static)#0.3.2 부터since 0.3.2소스source

완료 알림 설정.

Sets the finish callback.

complete_eventimpl FnMut() + 'static
다 드러나거나 skip_to_end 할 때 부를 함수.Function to call when everything is revealed or skip_to_end is called.

짝Counterpart: vanilla.js Typewriter.setCompleteEvent