vanilladocs
vanillapunch.com
API / animation/animator

animation/animator

애니메이터. (상태 기계로 스프라이트 클립을 고르고 섞는다)

  • 원본 animation/animator.js 를 옮긴 것이다. 상태(클립, 속도, 되풀이), 매개변수(실수, 정수, 참 거짓, 트리거), 전이(조건 목록, 종료 시각, 섞는 시간, 어느 상태에서나 넘어가는 전이), 매 프레임 tick 의 전이 판정과 크로스페이드 가중치가 원본과 같다.
  • 처음 더한 상태에서 시작한다. play 로 아무 상태로나 바로 옮길 수 있다. 전이의 from, to 는 Animator 상태 목록의 번호이고 from 이 None 이면 어느 상태에서나(Any State) 넘어간다.
  • tick 차례: 상태 시간을 흘린다(섞는 중이면 두 상태 모두) → 섞는 중이면 섞는 시간을 다 채웠을 때 다음 상태로 넘어간다 → 섞는 중이 아니면 어느 상태에서나 넘어가는 전이, 지금 상태에서 나가는 전이 차례로 넣은 순서대로 보고 처음 맞는 하나를 탄다. 섞는 동안에는 새 전이를 보지 않는다. 조건으로 쓴 트리거는 그 전이가 타면 풀린다.
  • 종료 시각은 나가는 상태의 정규화 시간이다. 그 시각을 지나는 갱신에서만 넘어갈 수 있고, 되풀이하는 상태에서 1 보다 작은 종료 시각은 바퀴마다 본다.
  • 원본과 다른 점:
  • 원본 getStates / get_transitions 는 List 를, 러스트 판은 조각(&[..])을 돌려준다. 원본 getParameters 의 사전은 get_parameters 가 이름과 AnimatorParameter 목록(넣은 차례)으로 돌려준다.
  • 원본 조건은 { parameterName, mode, threshold } 객체이고 러스트 판은 같은 필드의 AnimationCondition 이다. 원본 AnimationConditionMode 의 글 값은 열거 값이다.
  • 정수 매개변수는 i32, 실수와 기준 값은 원본 수처럼 f64 다. 정수를 기준 값과 견줄 때는 f64 로 바꿔 견준다.

Animator. (Picks and blends sprite clips with a state machine)

  • A port of the original animation/animator.js. States (clip, speed, loop), parameters (float, integer, boolean, trigger), transitions (condition list, exit time, blend time, transitions from any state), the transition check in each frame's tick, and the crossfade weights match the original.
  • It starts in the first added state. play moves to any state immediately. A transition's from and to are indices in the Animator state list, and a None from moves from any state (Any State).
  • tick order: advance the state time (both states while blending) → while blending, move to the next state once the blend time is filled → when not blending, check transitions from any state, then transitions leaving the current state, each in the order added, and take the first one that holds. No new transition is checked while blending. A trigger used as a condition is cleared when that transition is taken.
  • The exit time is the normalized time of the leaving state. The transition can only happen on the update that passes that time, and for a looping state an exit time below 1 is checked every cycle.
  • Differences from the original:
  • The original getStates / get_transitions return a List, the Rust version returns a slice (&[..]). The dictionary of the original getParameters is returned by get_parameters as a list of names and AnimatorParameter (in insertion order).
  • An original condition is a { parameterName, mode, threshold } object, the Rust version is an AnimationCondition with the same fields. The string values of the original AnimationConditionMode are enum values.
  • Integer parameters are i32, floats and thresholds are f64 like the original numbers. An integer is converted to f64 when compared with a threshold.

AnimationConditionstruct traits Clone, Debug, PartialEq

소스source

전이 조건. (원본 { parameterName, mode, threshold })

  • AnimationTransition::add_condition 이 만들어 넣고 get_conditions 로 읽는다. Animator::is_condition_satisfied 가 지금 매개변수로 본다.

Transition condition. (Original { parameterName, mode, threshold })

  • AnimationTransition::add_condition creates and adds it, get_conditions reads it. Animator::is_condition_satisfied checks it with the current parameters.
예제Example전이에 넣은 조건을 읽어 애니메이터로 보기Read a condition added to a transition and check it with an animator
use vanilla::{AnimationCondition, AnimationConditionMode, AnimationTransition, Animator};

let mut transition = AnimationTransition::new();
transition.add_condition("speed", AnimationConditionMode::Greater, 0.5);
let condition = &transition.get_conditions()[0];
assert_eq!(condition.parameter_name, "speed");
assert_eq!(condition.mode, AnimationConditionMode::Greater);
assert_eq!(condition.threshold, 0.5);

let mut animator = Animator::new();
assert!(!animator.is_condition_satisfied(condition));
animator.set_float("speed", 1.0);
assert!(animator.is_condition_satisfied(condition));
let slow = AnimationCondition { parameter_name: String::from("speed"), mode: AnimationConditionMode::Less, threshold: 0.5 };
assert!(!animator.is_condition_satisfied(&slow));
필드fieldpub parameter_name: String#0.4.0 부터since 0.4.0소스source

견줄 매개변수 이름.

Name of the parameter to compare.

반환ReturnsString

필드fieldpub mode: AnimationConditionMode#0.4.0 부터since 0.4.0소스source

견주는 법.

How to compare.

반환ReturnsAnimationConditionMode

필드fieldpub threshold: f64#0.4.0 부터since 0.4.0소스source

기준 값. (Greater, Less, Equals, NotEqual 에서 쓴다)

Threshold. (Used by Greater, Less, Equals, NotEqual)

반환Returnsf64

AnimationStatestruct traits Clone, Debug, PartialEq, Default

짝Counterpart: vanilla.js AnimationState소스source

애니메이션 상태. (클립 하나를 속도와 되풀이 여부로 튼다)

  • 상태 시간은 들어온 뒤 흐른 초에 속도를 곱해 쌓은 것이다. 정규화 시간은 상태 시간을 클립 길이로 나눈 것이다. (1 이면 한 바퀴)
  • 되풀이는 set_loop 로 정하지 않으면(None) 클립의 is_loop 를 따른다.
  • 클립이 없거나 길이가 0 이면 정규화 시간은 시간이 흐르기 전 0, 흐른 뒤 1 이다.

Animation state. (Plays one clip with a speed and a loop flag)

  • The state time is the seconds since entering, multiplied by the speed and accumulated. The normalized time is the state time divided by the clip length. (1 is one cycle)
  • If the loop is not set with set_loop (None), it follows the clip's is_loop.
  • With no clip or a zero length, the normalized time is 0 before any time passes and 1 after.
예제Example상태에 클립 달고 시간에 맞는 프레임 보기Attach a clip to a state and look up the frame for a time
use vanilla::{AnimationState, Rect};
use vanilla::resource::animationclip::AnimationClip;

let mut clip = AnimationClip::new();
clip.set_frames(vec![Rect::create(0.0, 0.0, 32.0, 32.0), Rect::create(32.0, 0.0, 32.0, 32.0)]);
clip.set_duration(0.5);
clip.set_loop(false);
let mut state = AnimationState::new();
state.set_clip(Some(clip));
state.set_speed(2.0);
assert!(!state.is_loop());
state.set_loop(Some(true));
assert!(state.is_loop());
assert_eq!(state.get_normalized_time(0.75), 1.5);
assert_eq!(state.get_frame_index(0.75), Some(1));
생성자constructorpub fn new() -> AnimationState#0.3.2 부터since 0.3.2소스source

생성. (클립 없음, 속도 1, 되풀이는 클립을 따름)

Create. (No clip, speed 1, loop follows the clip)

반환ReturnsAnimationState 클립이 없고 속도가 1 인 상태. (길이 0, 되풀이하지 않음)A state with no clip and speed 1. (Length 0, does not loop)

짝Counterpart: vanilla.js AnimationState.constructor

메서드methodpub fn set_clip(&mut self, clip: Option<AnimationClip>)#0.3.2 부터since 0.3.2소스source

클립 설정.

Sets the clip.

clipOption<AnimationClip>
이 상태에서 쓸 클립. (None 이면 비운다)Clip to use in this state. (None clears it)

짝Counterpart: vanilla.js AnimationState.setClip

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

클립 반환.

Returns the clip.

반환ReturnsOption<&AnimationClip> 이 상태의 클립. 없으면 None.Clip of this state. None when there is none.

짝Counterpart: vanilla.js AnimationState.getClip

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

재생 속도 설정.

Sets the playback speed.

speedf64
재생 속도. (기본 1, 2 면 두 배로 빠르고 0 이면 멈춘다)Playback speed. (Default 1, 2 plays twice as fast and 0 stops)

짝Counterpart: vanilla.js AnimationState.setSpeed

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

재생 속도 반환.

Get the playback speed.

반환Returnsf64 재생 속도. (기본 1)Playback speed. (Default 1)

짝Counterpart: vanilla.js AnimationState.getSpeed

메서드methodpub fn set_loop(&mut self, is_loop: Option<bool>)#0.4.0 부터since 0.4.0소스source

되풀이 여부 설정.

Set whether it loops.

is_loopOption<bool>
되풀이하면 참. (None 이면 클립의 is_loop 를 따른다, 기본 None)True to loop. (None follows the clip's is_loop, default None)

짝Counterpart: vanilla.js AnimationState.setLoop

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

되풀이 여부 반환.

Get whether it loops.

반환Returnsbool 되풀이하면 참. (set_loop 로 정하지 않았으면 클립의 is_loop, 클립도 없으면 거짓)True if it loops. (The clip's is_loop when not set with set_loop, false when there is no clip either)

짝Counterpart: vanilla.js AnimationState.isLoop

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

한 바퀴 길이 반환.

Get the length of one cycle.

반환Returnsf64 클립의 지속 시간. (초, 클립이 없으면 0)Duration of the clip. (Seconds, 0 when there is no clip)

짝Counterpart: vanilla.js AnimationState.getDuration

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

정규화 시간 반환.

Get the normalized time.

timef64
상태 시간. (초, 속도를 곱해 쌓은 것)State time. (Seconds, accumulated with the speed applied)

반환Returnsf64 상태 시간을 한 바퀴 길이로 나눈 것. (1 이면 한 바퀴, 되풀이하면 1 을 넘어 쌓인다. 길이가 0 이면 시간이 흐르기 전 0, 흐른 뒤 1)State time divided by the length of one cycle. (1 is one cycle, a looping state keeps accumulating past 1. With a zero length, 0 before any time passes and 1 after)

짝Counterpart: vanilla.js AnimationState.getNormalizedTime

메서드methodpub fn get_frame_index(&self, time: f64) -> Option<usize>#0.4.0 부터since 0.4.0소스source

프레임 번호 반환.

Get the frame index.

timef64
상태 시간. (초, 속도를 곱해 쌓은 것)State time. (Seconds, accumulated with the speed applied)

반환ReturnsOption<usize> 그 시간에 보일 클립 프레임의 번호. (0 부터, 되풀이하면 바퀴마다 처음부터, 아니면 끝 프레임에 머문다. 길이가 0 이면 0) 클립이나 프레임이 없으면 None.Index of the clip frame shown at that time. (From 0, a looping state restarts every cycle, otherwise it stays on the last frame. 0 for a zero length) None when there is no clip or no frames.

짝Counterpart: vanilla.js AnimationState.getFrameIndex

예제Example되풀이하는 상태와 끝에 머무는 상태A looping state and a state that stays at the end
use vanilla::{AnimationState, Rect};
use vanilla::resource::animationclip::AnimationClip;

let mut clip = AnimationClip::new();
clip.set_frames(vec![Rect::create(0.0, 0.0, 16.0, 16.0), Rect::create(16.0, 0.0, 16.0, 16.0), Rect::create(32.0, 0.0, 16.0, 16.0), Rect::create(48.0, 0.0, 16.0, 16.0)]);
clip.set_duration(1.0);
let mut state = AnimationState::new();
assert_eq!(state.get_frame_index(0.5), None);
state.set_clip(Some(clip));
state.set_loop(Some(true));
assert_eq!(state.get_frame_index(0.5), Some(2));
assert_eq!(state.get_frame_index(1.25), Some(1));
state.set_loop(Some(false));
assert_eq!(state.get_frame_index(1.25), Some(3));

AnimationTransitionstruct traits Clone, Debug, PartialEq, Default

짝Counterpart: vanilla.js AnimationTransition소스source

애니메이션 전이. (조건이 맞으면 대상 상태로 넘어가는 상태 사이의 연결, 상태는 Animator 상태 목록 번호)

  • from 이 None 이면 어느 상태에서나(Any State) 넘어간다. to 가 None 이거나 상태 목록 밖이면 쓰지 않는다.
  • 종료 시각(exit_time)은 나가는 상태의 정규화 시간이다. 정해 두면 그 시각을 지나는 갱신에서만 넘어갈 수 있다. 되풀이하는 상태에서 1 보다 작은 종료 시각은 바퀴마다 본다. (0.5 면 1.5, 2.5 에서도) 그 밖은 한 번만 본다.
  • 조건은 모두 맞아야 한다. 종료 시각도 조건도 없는 전이는 쓰지 않는다.
  • 섞는 시간(duration, 초)이 0 보다 크면 그동안 두 상태가 함께 흐르며 가중치가 선형으로 옮겨 간다. (크로스페이드)
  • 어느 상태에서나 넘어가는 전이가 지금 상태로 가는 경우는 can_transition_to_self 가 참일 때만 탄다. (기본 참, 다시 처음부터 튼다)

Animation transition. (A link between states that moves to the target state when its conditions hold, states are indices in the Animator state list)

  • With a None from, it moves from any state (Any State). A transition whose to is None or outside the state list is not used.
  • The exit time (exit_time) is the normalized time of the leaving state. When set, the transition can only happen on the update that passes that time. For a looping state, an exit time below 1 is checked every cycle (0.5 also at 1.5, 2.5). Otherwise it is checked only once.
  • All conditions must hold. A transition with neither an exit time nor conditions is not used.
  • If the blend time (duration, seconds) is above 0, both states run together for that time while the weight moves linearly. (Crossfade)
  • A transition from any state that leads to the current state is taken only when can_transition_to_self is true. (Default true, the state restarts from the beginning)
예제Example걷기에서 달리기로 가는 전이Transition from walking to running
use vanilla::{AnimationConditionMode, AnimationState, AnimationTransition, Animator};

let mut animator = Animator::new();
let walk_index = animator.add_state(AnimationState::new());
let run_index = animator.add_state(AnimationState::new());
let mut transition = AnimationTransition::new();
assert_eq!(transition.get_from(), None);
transition.set_from(Some(walk_index));
transition.set_to(Some(run_index));
transition.set_duration(0.2);
transition.add_condition("speed", AnimationConditionMode::Greater, 3.0);
let transition_index = animator.add_transition(transition);

let transition = &animator.get_transitions()[transition_index];
assert_eq!(transition.get_from(), Some(0));
assert_eq!(transition.get_to(), Some(1));
assert_eq!(transition.get_exit_time(), None);
assert_eq!(transition.get_duration(), 0.2);
assert!(transition.can_transition_to_self());
assert_eq!(transition.get_conditions()[0].mode, AnimationConditionMode::Greater);
생성자constructorpub fn new() -> AnimationTransition#0.3.2 부터since 0.3.2소스source

생성. (어느 상태에서나, 들어가는 상태 없음, 종료 시각 없음, 섞는 시간 0, 지금 상태로도 감)

Create. (From any state, no entering state, no exit time, blend time 0, may lead to the current state)

반환ReturnsAnimationTransition 조건이 없는 빈 전이. (들어가는 상태를 정하고 종료 시각이나 조건을 넣어야 쓰인다)An empty transition with no conditions. (It is used once the entering state is set and an exit time or a condition is added)

짝Counterpart: vanilla.js AnimationTransition.constructor

메서드methodpub fn set_from(&mut self, from: Option<usize>)#0.3.2 부터since 0.3.2소스source

나가는 상태 설정. (Animator::add_state 가 돌려준 번호)

Set the leaving state. (The index returned by Animator::add_state)

fromOption<usize>
나가는 상태의 번호. (None 이면 어느 상태에서나, 기본 None)Index of the leaving state. (None means any state, default None)

짝Counterpart: vanilla.js AnimationTransition.setFrom

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

나가는 상태 반환.

Get the leaving state.

반환ReturnsOption<usize> 나가는 상태의 번호. 어느 상태에서나 넘어가면 None.Index of the leaving state. None when it moves from any state.

짝Counterpart: vanilla.js AnimationTransition.getFrom

메서드methodpub fn set_to(&mut self, to: Option<usize>)#0.3.2 부터since 0.3.2소스source

들어가는 상태 설정. (Animator::add_state 가 돌려준 번호)

Set the entering state. (The index returned by Animator::add_state)

toOption<usize>
들어가는 상태의 번호. (None 이면 비우고, 빈 전이는 쓰지 않는다)Index of the entering state. (None clears it, an empty transition is not used)

짝Counterpart: vanilla.js AnimationTransition.setTo

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

들어가는 상태 반환.

Get the entering state.

반환ReturnsOption<usize> 들어가는 상태의 번호. 정하지 않았으면 None.Index of the entering state. None when not set.

짝Counterpart: vanilla.js AnimationTransition.getTo

메서드methodpub fn set_exit_time(&mut self, exit_time: Option<f64>)#0.4.0 부터since 0.4.0소스source

종료 시각 설정.

Set the exit time.

exit_timeOption<f64>
나가는 상태의 정규화 시간. (1 이면 한 바퀴 끝, None 이면 종료 시각 없이 조건만 본다, 기본 None)Normalized time of the leaving state. (1 is the end of one cycle, None checks only the conditions without an exit time, default None)

짝Counterpart: vanilla.js AnimationTransition.setExitTime

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

종료 시각 반환.

Get the exit time.

반환ReturnsOption<f64> 종료 시각. (정규화 시간, 없으면 None)Exit time. (Normalized time, None when there is none)

짝Counterpart: vanilla.js AnimationTransition.getExitTime

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

섞는 시간 설정.

Set the blend time.

durationf64
두 상태를 섞는 시간. (초, 0 이하이면 바로 넘어간다, 기본 0)Time to blend the two states. (Seconds, 0 or less moves immediately, default 0)

짝Counterpart: vanilla.js AnimationTransition.setDuration

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

섞는 시간 반환.

Get the blend time.

반환Returnsf64 섞는 시간. (초)Blend time. (Seconds)

짝Counterpart: vanilla.js AnimationTransition.getDuration

메서드methodpub fn set_can_transition_to_self(&mut self, can_transition_to_self: bool)#0.4.0 부터since 0.4.0소스source

지금 상태로 가는 것을 허락할지 설정.

Set whether moving to the current state is allowed.

can_transition_to_selfbool
참이면 어느 상태에서나 넘어가는 전이가 지금 상태로도 간다. (기본 참, from 이 정해진 전이에는 쓰지 않는다)True lets a transition from any state also lead to the current state. (Default true, not used by transitions with a set from)

짝Counterpart: vanilla.js AnimationTransition.setCanTransitionToSelf

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

지금 상태로 가는 것을 허락하는지 반환.

Get whether moving to the current state is allowed.

반환Returnsbool 어느 상태에서나 넘어가는 전이가 지금 상태로도 가면 참.True if a transition from any state also leads to the current state.

짝Counterpart: vanilla.js AnimationTransition.canTransitionToSelf

메서드methodpub fn add_condition(&mut self, parameter_name: &str, mode: AnimationConditionMode, threshold: f64)#0.4.0 부터since 0.4.0소스source

조건 추가.

Add a condition.

parameter_name&str
견줄 매개변수 이름.Name of the parameter to compare.
modeAnimationConditionMode
견주는 법.How to compare.
thresholdf64
기준 값. (Greater, Less, Equals, NotEqual 에서 쓴다, 원본 기본 0)Threshold. (Used by Greater, Less, Equals, NotEqual, original default 0)

짝Counterpart: vanilla.js AnimationTransition.addCondition

메서드methodpub fn get_conditions(&self) -> &[AnimationCondition]#0.4.0 부터since 0.4.0소스source

조건 목록 반환.

Get the condition list.

반환Returns&[AnimationCondition] 넣은 차례의 조건 목록.Conditions in the order they were added.

짝Counterpart: vanilla.js AnimationTransition.getConditions

메서드methodpub fn is_exit_time_reached(&self, state: &AnimationState, previous_time: f64, current_time: f64) -> bool#0.4.0 부터since 0.4.0소스source

종료 시각을 지났는지 반환.

Get whether the exit time was passed.

state&AnimationState
나가는 상태.Leaving state.
previous_timef64
이번 갱신 앞의 상태 시간. (초)State time before this update. (Seconds)
current_timef64
이번 갱신 뒤의 상태 시간. (초)State time after this update. (Seconds)

반환Returnsbool 종료 시각이 없거나, 이번 갱신에서 종료 시각을 지났으면 참. (길이가 0 인 상태는 들어온 뒤 첫 갱신에서 지난다)True if there is no exit time, or this update passed the exit time. (A zero-length state passes it on the first update after entering)

짝Counterpart: vanilla.js AnimationTransition.isExitTimeReached

예제Example되풀이하는 상태에서 바퀴마다 보는 종료 시각An exit time checked every cycle in a looping state
use vanilla::{AnimationState, AnimationTransition, Rect};
use vanilla::resource::animationclip::AnimationClip;

let mut clip = AnimationClip::new();
clip.set_frames(vec![Rect::create(0.0, 0.0, 32.0, 32.0)]);
clip.set_duration(2.0);
clip.set_loop(true);
let mut state = AnimationState::new();
state.set_clip(Some(clip));

let mut transition = AnimationTransition::new();
assert!(transition.is_exit_time_reached(&state, 0.0, 0.5));
transition.set_exit_time(Some(0.5));
assert!(!transition.is_exit_time_reached(&state, 0.0, 0.5));
assert!(transition.is_exit_time_reached(&state, 0.5, 1.5));
assert!(transition.is_exit_time_reached(&state, 2.5, 3.5));
state.set_loop(Some(false));
assert!(!transition.is_exit_time_reached(&state, 2.5, 3.5));

Animatorstruct traits Default

짝Counterpart: vanilla.js Animator소스source

애니메이터. (상태 기계로 스프라이트 클립을 고르고 섞는다)

  • 매개변수는 실수(set_float), 정수(set_integer), 참 거짓(set_bool), 트리거(set_trigger) 넷이다. 같은 이름을 다른 종류로 넣으면 종류째 바꾼다. 트리거는 그 트리거를 조건으로 쓴 전이가 타면 풀린다. (reset_trigger 로 직접 풀 수도 있다)
  • 섞는 중의 가중치: 다음 상태가 get_transition_weight(섞은 시간 / 섞는 시간), 지금 상태가 1 - 그 값이다.
  • 고른 프레임은 get_current_frame, get_next_frame 으로 꺼낸다. (클립 프레임 목록의 영역)

Animator. (Picks and blends sprite clips with a state machine)

  • There are four parameter kinds: float (set_float), integer (set_integer), boolean (set_bool), and trigger (set_trigger). Setting the same name with another kind replaces the kind. A trigger is cleared when a transition that uses it as a condition is taken. (reset_trigger also clears it)
  • Weights while blending: the next state gets get_transition_weight (blended time / blend time) and the current state gets 1 minus that.
  • The chosen frames come from get_current_frame and get_next_frame. (Rects of the clip frame list)
예제Example속도로 걷기와 달리기를 오가는 애니메이터Animator that switches between walking and running by speed
use vanilla::{AnimationConditionMode, AnimationState, AnimationTransition, Animator, Rect};
use vanilla::resource::animationclip::AnimationClip;

let mut walk_clip = AnimationClip::new();
walk_clip.set_frames(vec![Rect::create(0.0, 0.0, 32.0, 32.0), Rect::create(32.0, 0.0, 32.0, 32.0)]);
walk_clip.set_duration(1.0);
walk_clip.set_loop(true);
let mut run_clip = AnimationClip::new();
run_clip.set_frames(vec![Rect::create(0.0, 32.0, 32.0, 32.0), Rect::create(32.0, 32.0, 32.0, 32.0)]);
run_clip.set_duration(0.5);
run_clip.set_loop(true);

let mut animator = Animator::new();
let mut walk_state = AnimationState::new();
walk_state.set_clip(Some(walk_clip));
let mut run_state = AnimationState::new();
run_state.set_clip(Some(run_clip));
let walk_index = animator.add_state(walk_state);
let run_index = animator.add_state(run_state);
let mut to_run = AnimationTransition::new();
to_run.set_from(Some(walk_index));
to_run.set_to(Some(run_index));
to_run.set_duration(0.25);
to_run.add_condition("speed", AnimationConditionMode::Greater, 3.0);
animator.add_transition(to_run);
let mut to_walk = AnimationTransition::new();
to_walk.set_from(Some(run_index));
to_walk.set_to(Some(walk_index));
to_walk.add_condition("speed", AnimationConditionMode::Less, 1.0);
animator.add_transition(to_walk);

animator.set_float("speed", 5.0);
animator.tick(0.125);
assert_eq!(animator.get_current_state_index(), Some(walk_index));
assert_eq!(animator.get_next_state_index(), Some(run_index));
assert_eq!(animator.get_transition_weight(), 0.0);
animator.tick(0.125);
assert_eq!(animator.get_next_state_index(), Some(run_index));
assert_eq!(animator.get_transition_weight(), 0.5);
animator.tick(0.125);
let frame = animator.get_current_frame().expect("frame");
assert_eq!(animator.get_current_state_index(), Some(run_index));
assert!(!animator.is_in_transition());
assert_eq!(frame.position.y, 32.0);
예제Example트리거로 어느 상태에서나(Any State) 넘어가는 피격과 종료 시각으로 돌아오기A trigger-driven hit from any state (Any State), returning by exit time
use vanilla::{AnimationConditionMode, AnimationState, AnimationTransition, Animator, Rect};
use vanilla::resource::animationclip::AnimationClip;

fn create_state(duration: f64, is_loop: bool) -> AnimationState {
	let mut clip = AnimationClip::new();
	clip.set_frames(vec![Rect::create(0.0, 0.0, 32.0, 32.0), Rect::create(32.0, 0.0, 32.0, 32.0)]);
	clip.set_duration(duration);
	clip.set_loop(is_loop);
	let mut state = AnimationState::new();
	state.set_clip(Some(clip));
	state
}

let mut animator = Animator::new();
let idle_index = animator.add_state(create_state(1.0, true));
let run_index = animator.add_state(create_state(0.5, true));
let hit_index = animator.add_state(create_state(0.5, false));
let mut to_run = AnimationTransition::new();
to_run.set_from(Some(idle_index));
to_run.set_to(Some(run_index));
to_run.add_condition("isRunning", AnimationConditionMode::If, 0.0);
animator.add_transition(to_run);
let mut any_to_hit = AnimationTransition::new();
any_to_hit.set_to(Some(hit_index));
any_to_hit.set_can_transition_to_self(false);
any_to_hit.add_condition("hit", AnimationConditionMode::If, 0.0);
animator.add_transition(any_to_hit);
let mut hit_to_idle = AnimationTransition::new();
hit_to_idle.set_from(Some(hit_index));
hit_to_idle.set_to(Some(idle_index));
hit_to_idle.set_exit_time(Some(1.0));
animator.add_transition(hit_to_idle);

animator.set_bool("isRunning", true);
animator.tick(0.1);
assert_eq!(animator.get_current_state_index(), Some(run_index));
animator.set_trigger("hit");
animator.tick(0.1);
assert_eq!(animator.get_current_state_index(), Some(hit_index));
assert!(!animator.get_trigger("hit"));

animator.set_trigger("hit");
animator.tick(0.1);
assert_eq!(animator.get_current_state_index(), Some(hit_index));
assert!(animator.get_trigger("hit"));
animator.reset_trigger("hit");
animator.set_bool("isRunning", false);
animator.tick(0.5);
assert_eq!(animator.get_current_state_index(), Some(idle_index));
생성자constructorpub fn new() -> Animator#0.3.2 부터since 0.3.2소스source

생성. (상태 없음)

Create. (No states)

반환ReturnsAnimator 상태, 전이, 매개변수가 없는 애니메이터. (지금 상태가 None 이라 tick 이 아무것도 하지 않는다)An animator with no states, transitions, or parameters. (The current state is None, so tick does nothing)

짝Counterpart: vanilla.js Animator.constructor

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

갱신.

Update.

time_deltaf64
지난 프레임부터의 시간. (초, 상태마다 속도를 곱해 흘린다)Time since the last frame. (Seconds, each state applies its speed)

짝Counterpart: vanilla.js Animator.tick

메서드methodpub fn play(&mut self, state_index: usize)#0.4.0 부터since 0.4.0소스source

상태 바로 틀기. (섞지 않고 처음부터)

Play a state immediately. (From the beginning, without blending)

state_indexusize
틀 상태의 번호. (add_state 가 돌려준 것, 목록 밖이면 무시한다)Index of the state to play. (Returned by add_state, ignored when outside the list)

짝Counterpart: vanilla.js Animator.play

예제Example섞는 중에도 바로 옮기고, 목록 밖 번호는 무시Moves immediately even while blending, and ignores an index outside the list
use vanilla::{AnimationConditionMode, AnimationState, AnimationTransition, Animator};

let mut animator = Animator::new();
let idle_index = animator.add_state(AnimationState::new());
let jump_index = animator.add_state(AnimationState::new());
let mut transition = AnimationTransition::new();
transition.set_from(Some(idle_index));
transition.set_to(Some(jump_index));
transition.set_duration(0.5);
transition.add_condition("jump", AnimationConditionMode::If, 0.0);
animator.add_transition(transition);
animator.set_trigger("jump");
animator.tick(0.1);
assert!(animator.is_in_transition());

animator.play(idle_index);
assert_eq!(animator.get_current_state_index(), Some(idle_index));
assert!(!animator.is_in_transition());
assert_eq!(animator.get_current_normalized_time(), 0.0);
animator.play(99);
assert_eq!(animator.get_current_state_index(), Some(idle_index));
메서드methodpub fn find_transition(&self, previous_time: f64) -> Option<usize>#0.4.0 부터since 0.4.0소스source

탈 전이 찾기.

Find the transition to take.

previous_timef64
이번 갱신 앞의 지금 상태 시간. (초, 종료 시각을 지났는지 볼 때 쓴다)Current state time before this update. (Seconds, used to check whether the exit time was passed)

반환ReturnsOption<usize> 처음 맞는 전이의 번호. (어느 상태에서나 넘어가는 전이를 먼저, 그다음 지금 상태에서 나가는 전이를 넣은 순서대로 본다) 섞는 중이거나 없으면 None.Index of the first transition that holds. (Transitions from any state are checked first, then transitions leaving the current state, each in the order added) None while blending or when none holds.

짝Counterpart: vanilla.js Animator.findTransition

메서드methodpub fn start_transition(&mut self, transition_index: usize)#0.4.0 부터since 0.4.0소스source

전이 타기. (조건과 종료 시각은 보지 않는다)

Take a transition. (Conditions and exit time are not checked)

transition_indexusize
탈 전이의 번호. (add_transition 이 돌려준 것, 목록 밖이거나 들어가는 상태가 목록 밖이면 무시한다)Index of the transition to take. (Returned by add_transition, ignored when outside the list or when the entering state is outside the list)

짝Counterpart: vanilla.js Animator.startTransition

메서드methodpub fn is_condition_satisfied(&self, condition: &AnimationCondition) -> bool#0.4.0 부터since 0.4.0소스source

조건이 맞는지 반환.

Get whether a condition holds.

condition&AnimationCondition
볼 조건. (AnimationTransition::get_conditions 의 요소)Condition to check. (An entry of AnimationTransition::get_conditions)

반환Returnsbool 지금 매개변수로 조건이 맞으면 참. (매개변수가 없거나 견줄 수 없는 종류면 거짓)True if the condition holds with the current parameters. (False when the parameter is missing or its kind cannot be compared)

짝Counterpart: vanilla.js Animator.isConditionSatisfied

메서드methodpub fn set_float(&mut self, name: &str, value: f64)#0.4.0 부터since 0.4.0소스source

실수 매개변수 설정.

Set a float parameter.

name&str
매개변수 이름.Parameter name.
valuef64
값. (같은 이름이 있으면 종류째 바꾼다)Value. (Replaces the kind when the same name exists)

짝Counterpart: vanilla.js Animator.setFloat

예제Example종류별 매개변수 넣고 읽기Set and read parameters of each kind
use vanilla::Animator;

let mut animator = Animator::new();
animator.set_float("speed", 1.5);
animator.set_integer("combo", 3);
animator.set_bool("isGrounded", true);
animator.set_trigger("jump");
assert_eq!(animator.get_float("speed"), 1.5);
assert_eq!(animator.get_integer("combo"), 3);
assert!(animator.get_bool("isGrounded"));
assert!(animator.get_trigger("jump"));

assert_eq!(animator.get_float("combo"), 0.0);
assert_eq!(animator.get_float("missing"), 0.0);
animator.set_bool("speed", false);
assert_eq!(animator.get_float("speed"), 0.0);
animator.reset_trigger("jump");
assert!(!animator.get_trigger("jump"));
메서드methodpub fn get_float(&self, name: &str) -> f64#0.4.0 부터since 0.4.0소스source

실수 매개변수 반환.

Get a float parameter.

name&str
매개변수 이름.Parameter name.

반환Returnsf64 값. (없거나 실수가 아니면 0)Value. (0 when missing or not a float)

짝Counterpart: vanilla.js Animator.getFloat

메서드methodpub fn set_integer(&mut self, name: &str, value: i32)#0.4.0 부터since 0.4.0소스source

정수 매개변수 설정.

Set an integer parameter.

name&str
매개변수 이름.Parameter name.
valuei32
값. (같은 이름이 있으면 종류째 바꾼다)Value. (Replaces the kind when the same name exists)

짝Counterpart: vanilla.js Animator.setInteger

메서드methodpub fn get_integer(&self, name: &str) -> i32#0.4.0 부터since 0.4.0소스source

정수 매개변수 반환.

Get an integer parameter.

name&str
매개변수 이름.Parameter name.

반환Returnsi32 값. (없거나 정수가 아니면 0)Value. (0 when missing or not an integer)

짝Counterpart: vanilla.js Animator.getInteger

메서드methodpub fn set_bool(&mut self, name: &str, value: bool)#0.4.0 부터since 0.4.0소스source

참 거짓 매개변수 설정.

Set a boolean parameter.

name&str
매개변수 이름.Parameter name.
valuebool
값. (같은 이름이 있으면 종류째 바꾼다)Value. (Replaces the kind when the same name exists)

짝Counterpart: vanilla.js Animator.setBool

메서드methodpub fn get_bool(&self, name: &str) -> bool#0.4.0 부터since 0.4.0소스source

참 거짓 매개변수 반환.

Get a boolean parameter.

name&str
매개변수 이름.Parameter name.

반환Returnsbool 값. (없거나 참 거짓이 아니면 거짓)Value. (False when missing or not a boolean)

짝Counterpart: vanilla.js Animator.getBool

메서드methodpub fn set_trigger(&mut self, name: &str)#0.4.0 부터since 0.4.0소스source

트리거 걸기. (그 트리거를 조건으로 쓴 전이가 타면 풀린다)

Set a trigger. (Cleared when a transition that uses it as a condition is taken)

name&str
매개변수 이름. (같은 이름이 있으면 종류째 바꾼다)Parameter name. (Replaces the kind when the same name exists)

짝Counterpart: vanilla.js Animator.setTrigger

메서드methodpub fn reset_trigger(&mut self, name: &str)#0.4.0 부터since 0.4.0소스source

트리거 풀기.

Clear a trigger.

name&str
매개변수 이름. (같은 이름이 있으면 종류째 바꾼다)Parameter name. (Replaces the kind when the same name exists)

짝Counterpart: vanilla.js Animator.resetTrigger

메서드methodpub fn get_trigger(&self, name: &str) -> bool#0.4.0 부터since 0.4.0소스source

트리거가 걸려 있는지 반환.

Get whether a trigger is set.

name&str
매개변수 이름.Parameter name.

반환Returnsbool 걸려 있으면 참. (없거나 트리거가 아니면 거짓)True if set. (False when missing or not a trigger)

짝Counterpart: vanilla.js Animator.getTrigger

메서드methodpub fn get_parameters(&self) -> Vec<(&str, AnimatorParameter)>#0.4.0 부터since 0.4.0소스source

모든 매개변수 반환. (원본 getParameters 의 사전, 처음 넣은 차례)

Returns all parameters. (the dictionary of the original getParameters, in first insertion order)

반환ReturnsVec<(&str, AnimatorParameter)> 이름과 매개변수(종류와 값) 목록. (처음 넣은 차례, 같은 이름을 다시 넣어도 자리는 그대로)List of names and parameters (kind and value). (in first insertion order, setting the same name again keeps its place)

짝Counterpart: vanilla.js Animator.getParameters

예제Example넣은 차례로 이름과 값 보기See names and values in insertion order
use vanilla::{Animator, AnimatorParameter};

let mut animator = Animator::new();
animator.set_float("speed", 1.5);
animator.set_trigger("jump");
animator.set_bool("speed", true);
assert_eq!(animator.get_parameters(), vec![("speed", AnimatorParameter::Bool(true)), ("jump", AnimatorParameter::Trigger(true))]);
메서드methodpub fn add_state(&mut self, state: AnimationState) -> usize#0.3.2 부터since 0.3.2소스source

상태 더하기. (처음 더한 상태에서 시작한다)

Add a state. (It starts in the first added state)

stateAnimationState
더할 상태.State to add.

반환Returnsusize 더한 상태의 번호. (0 부터)Index of the added state. (From 0)

짝Counterpart: vanilla.js Animator.addState

메서드methodpub fn get_states(&self) -> &[AnimationState]#0.3.2 부터since 0.3.2소스source

상태 목록 반환.

Returns the state list.

반환Returns&[AnimationState] 상태 목록.State list.

짝Counterpart: vanilla.js Animator.getStates

메서드methodpub fn add_transition(&mut self, transition: AnimationTransition) -> usize#0.3.2 부터since 0.3.2소스source

전이 더하기.

Add a transition.

transitionAnimationTransition
더할 전이.Transition to add.

반환Returnsusize 더한 전이의 번호. (0 부터)Index of the added transition. (From 0)

짝Counterpart: vanilla.js Animator.addTransition

메서드methodpub fn get_transitions(&self) -> &[AnimationTransition]#0.3.2 부터since 0.3.2소스source

전이 목록 반환.

Get the transition list.

반환Returns&[AnimationTransition] 전이 목록.Transition list.

짝Counterpart: vanilla.js Animator.getTransitions

메서드methodpub fn get_current_state_index(&self) -> Option<usize>#0.4.0 부터since 0.4.0소스source

지금 상태 반환.

Get the current state.

반환ReturnsOption<usize> 지금 상태의 번호. (섞는 중이면 나가는 상태) 상태가 없으면 None.Index of the current state. (The leaving state while blending) None when there are no states.

짝Counterpart: vanilla.js Animator.getCurrentStateIndex

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

지금 상태의 정규화 시간 반환.

Get the normalized time of the current state.

반환Returnsf64 지금 상태 시간을 한 바퀴 길이로 나눈 것. (상태가 없으면 0)Current state time divided by the length of one cycle. (0 when there are no states)

짝Counterpart: vanilla.js Animator.getCurrentNormalizedTime

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

지금 상태의 프레임 반환.

Get the frame of the current state.

반환ReturnsOption<&Rect> 지금 상태 시간에 보일 클립 프레임의 영역. 상태나 클립이나 프레임이 없으면 None.Rect of the clip frame shown at the current state time. None when there is no state, clip, or frame.

짝Counterpart: vanilla.js Animator.getCurrentFrame

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

섞는 중인지 반환.

Get whether it is blending.

반환Returnsbool 두 상태를 섞는 중이면 참.True while blending two states.

짝Counterpart: vanilla.js Animator.isInTransition

메서드methodpub fn get_next_state_index(&self) -> Option<usize>#0.4.0 부터since 0.4.0소스source

섞으며 들어가는 상태 반환.

Get the state being blended in.

반환ReturnsOption<usize> 들어가는 상태의 번호. 섞는 중이 아니면 None.Index of the entering state. None when not blending.

짝Counterpart: vanilla.js Animator.getNextStateIndex

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

들어가는 상태의 정규화 시간 반환.

Get the normalized time of the entering state.

반환Returnsf64 들어가는 상태 시간을 한 바퀴 길이로 나눈 것. (섞는 중이 아니면 0)Entering state time divided by the length of one cycle. (0 when not blending)

짝Counterpart: vanilla.js Animator.getNextNormalizedTime

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

들어가는 상태의 프레임 반환.

Get the frame of the entering state.

반환ReturnsOption<&Rect> 들어가는 상태 시간에 보일 클립 프레임의 영역. 섞는 중이 아니거나 클립이나 프레임이 없으면 None.Rect of the clip frame shown at the entering state time. None when not blending or when there is no clip or frame.

짝Counterpart: vanilla.js Animator.getNextFrame

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

들어가는 상태의 가중치 반환. (크로스페이드)

Get the weight of the entering state. (Crossfade)

반환Returnsf64 섞은 시간 / 섞는 시간. (0 ~ 1, 지금 상태의 가중치는 1 - 이 값, 섞는 중이 아니면 0)Blended time / blend time. (0 to 1, the current state's weight is 1 minus this, 0 when not blending)

짝Counterpart: vanilla.js Animator.getTransitionWeight

예제Example0.5 초 동안 두 상태를 섞는 크로스페이드A crossfade blending two states over 0.5 seconds
use vanilla::{AnimationConditionMode, AnimationState, AnimationTransition, Animator, Rect};
use vanilla::resource::animationclip::AnimationClip;

let mut animator = Animator::new();
let walk_index = animator.add_state(AnimationState::new());
let mut run_clip = AnimationClip::new();
run_clip.set_frames(vec![Rect::create(0.0, 32.0, 32.0, 32.0), Rect::create(32.0, 32.0, 32.0, 32.0)]);
run_clip.set_duration(1.0);
run_clip.set_loop(true);
let mut run_state = AnimationState::new();
run_state.set_clip(Some(run_clip));
let run_index = animator.add_state(run_state);
let mut transition = AnimationTransition::new();
transition.set_from(Some(walk_index));
transition.set_to(Some(run_index));
transition.set_duration(0.5);
transition.add_condition("speed", AnimationConditionMode::Greater, 1.0);
animator.add_transition(transition);

animator.set_float("speed", 2.0);
animator.tick(0.1);
assert!(animator.is_in_transition());
assert_eq!(animator.get_transition_weight(), 0.0);
animator.tick(0.25);
let next_weight = animator.get_transition_weight();
assert_eq!(next_weight, 0.5);
assert_eq!(1.0 - next_weight, 0.5);
assert_eq!(animator.get_next_normalized_time(), 0.25);
assert_eq!(animator.get_next_frame().map(|frame| frame.position.x), Some(0.0));
animator.tick(0.25);
assert_eq!(animator.get_current_state_index(), Some(run_index));
assert_eq!(animator.get_transition_weight(), 0.0);
assert_eq!(animator.get_current_frame().map(|frame| frame.position.x), Some(32.0));

AnimationConditionModeenum traits Clone, Copy, Debug, PartialEq, Eq

짝Counterpart: vanilla.js AnimationConditionMode소스source

전이 조건의 견주는 법.

  • If, IfNot 은 참 거짓 매개변수를 본다. (If 는 트리거가 걸려 있는 것도 본다)
  • Greater, Less, Equals, NotEqual 은 실수와 정수 매개변수를 기준 값과 견준다.
  • 매개변수가 없거나 견줄 수 없는 종류면(참 거짓에 Greater 같은) 맞지 않은 것이다.

How a transition condition compares.

  • If and IfNot look at boolean parameters. (If also looks at whether a trigger is set)
  • Greater, Less, Equals, NotEqual compare float and integer parameters with the threshold.
  • A missing parameter or a kind that cannot be compared (Greater on a boolean and so on) does not hold.
예제Example견주는 법마다 매개변수를 보는 결과What each comparison mode gives for the parameters
use vanilla::{AnimationCondition, AnimationConditionMode, Animator};

let mut animator = Animator::new();
animator.set_integer("combo", 3);
animator.set_bool("isGrounded", false);
animator.set_trigger("jump");
let check = |parameter_name: &str, mode: AnimationConditionMode, threshold: f64| {
	animator.is_condition_satisfied(&AnimationCondition { parameter_name: parameter_name.to_string(), mode, threshold })
};
assert!(check("jump", AnimationConditionMode::If, 0.0));
assert!(check("isGrounded", AnimationConditionMode::IfNot, 0.0));
assert!(check("combo", AnimationConditionMode::Greater, 2.0));
assert!(!check("combo", AnimationConditionMode::Less, 3.0));
assert!(check("combo", AnimationConditionMode::Equals, 3.0));
assert!(!check("combo", AnimationConditionMode::NotEqual, 3.0));
assert!(!check("isGrounded", AnimationConditionMode::Greater, 0.0));
assert!(!check("missing", AnimationConditionMode::If, 0.0));
이름Name설명Description
If참 거짓 매개변수가 참이거나 트리거가 걸려 있다.The boolean parameter is true or the trigger is set.
IfNot참 거짓 매개변수가 거짓이다.The boolean parameter is false.
Greater수 매개변수가 기준 값보다 크다.The number parameter is greater than the threshold.
Less수 매개변수가 기준 값보다 작다.The number parameter is less than the threshold.
Equals수 매개변수가 기준 값과 같다.The number parameter equals the threshold.
NotEqual수 매개변수가 기준 값과 다르다.The number parameter differs from the threshold.

AnimatorParameterenum traits Clone, Copy, Debug, PartialEq

소스source

애니메이터 매개변수. (원본 { type, value }, 트리거는 걸려 있는지, Animator::get_parameters 가 돌려준다)

Animator parameter. (the original { type, value }, for a trigger whether it is set, returned by Animator::get_parameters)

예제Example종류와 값 꺼내기Read the kind and value
use vanilla::{Animator, AnimatorParameter};

let mut animator = Animator::new();
animator.set_integer("combo", 2);
assert_eq!(animator.get_parameters(), vec![("combo", AnimatorParameter::Int(2))]);
이름Name값Value설명Description
FloatFloat(f64)실수. (원본 type "float")Float. (the original type "float")
IntInt(i32)정수. (원본 type "int")Integer. (the original type "int")
BoolBool(bool)참 거짓. (원본 type "bool")Boolean. (the original type "bool")
TriggerTrigger(bool)트리거. (원본 type "trigger", 값은 걸려 있는지)Trigger. (the original type "trigger", the value is whether it is set)