misc/spriteanimator
스프라이트 애니메이터 컴포넌트.
- 원본 misc/spriteanimator.js 를 옮긴 것이다. 이름을 붙인 클립(프레임 시퀀스)을 등록해 두고 play("run") 으로 바꾼다.
- 같은 클립을 다시 play 해도 처음부터 하지 않는다. (restart_if_same 으로 바꿀 수 있다)
- 클립이 끝나면 on_complete 콜백으로 다음 상태를 이어 간다. (FSM 과 묶어 쓴다)
- 같은 노드의 Sprite 컴포넌트에 지금 프레임(이미지 + 영역)을 넣는다. 원본 findSprite 처럼 한 번 찾으면 기억한다. (find_sprite)
- 사용:
let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
animator.add_clip("idle", image.clone(), &idleRects, 10.0, true);
animator.add_clip("attack", image.clone(), &attackRects, 12.0, false);
SpriteAnimator::play(&mut node_tree[hero_id], "attack", SpriteAnimatorPlayOptions::create_with_on_complete(|animator| {
animator.play_clip("idle", SpriteAnimatorPlayOptions::default());
}));- play 는 원본처럼 그 자리에서 Sprite 에 첫 프레임을 넣는다. 러스트 컴포넌트는 자기 노드를 가리키지 않아(노드는 NodeTree 가 든다) 노드를 받는다. SpriteAnimator::play(&mut node, "run", 옵션) 노드 없이 애니메이터만 있을 때(완료 콜백 안)는 play_clip 이다. 완료 콜백 뒤에는 같은 tick 에 프레임을 넣어 원본처럼 바로 바뀐다.
- 원본과 다른 점: on_complete 는 애니메이터를 받는 한 번짜리 콜백(FnOnce(&mut SpriteAnimator))이다. 원본은 클로저가 애니메이터를 붙잡아 썼다. fps 는 이름을 줄이지 않아 frame_per_second 다. 기본값(10, 반복)은 DEFAULT_FRAME_PER_SECOND 와 true 를 넘긴다. 아틀라스 JSON 은 serde_json::Value 로 받는다. 원본 findSprite 는 찾은 Sprite 를 들고 있는다. 러스트 컴포넌트는 형제 컴포넌트의 참조를 들 수 없어(빌림이 tick 을 넘어 살 수 없다) Sprite 가 든 노드의 NodeId 를 기억하고, SpriteAnimator::find_sprite(&mut node_tree, 노드) 가 그 노드에서 꺼낸다. 밖에서는 apply_current_frame(sprite) 에 Sprite 를 넘길 수도 있다.
Sprite animator component.
- A port of the original misc/spriteanimator.js. Register named clips (frame sequences) and switch with play("run").
- Playing the same clip again does not restart it. (can be changed with restart_if_same)
- When a clip ends, the on_complete callback continues to the next state. (used together with an FSM)
- Puts the current frame (image + area) into the Sprite component of the same node. Remembers it once found, like the original findSprite. (find_sprite)
- Usage:
let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
animator.add_clip("idle", image.clone(), &idleRects, 10.0, true);
animator.add_clip("attack", image.clone(), &attackRects, 12.0, false);
SpriteAnimator::play(&mut node_tree[hero_id], "attack", SpriteAnimatorPlayOptions::create_with_on_complete(|animator| {
animator.play_clip("idle", SpriteAnimatorPlayOptions::default());
}));- play puts the first frame into the Sprite right away, as in the original. A Rust component does not point to its own node (the NodeTree holds nodes), so it takes the node. SpriteAnimator::play(&mut node, "run", options) With only the animator and no node (inside the complete callback), use play_clip. After the complete callback the frame goes in during the same tick, so it changes right away as in the original.
- Differences from the original: on_complete is a one-shot callback that receives the animator (FnOnce(&mut SpriteAnimator)). In the original, the closure captured the animator. fps is not abbreviated, so it is frame_per_second. The defaults (10, looping) are passed as DEFAULT_FRAME_PER_SECOND and true. Atlas JSON is taken as serde_json::Value. The original findSprite holds the Sprite it found. A Rust component cannot hold a reference to a sibling component (a borrow cannot live past tick), so it remembers the NodeId of the node holding the Sprite, and SpriteAnimator::find_sprite(&mut node_tree, node) takes it out of that node. From outside, a Sprite can also be passed to apply_current_frame(sprite).
SpriteAnimatorPlayOptionsstruct traits Default
재생 설정. (원본 options = { on_complete?, restart_if_same = false })
- 기본값은 콜백 없음, 같은 클립이면 다시 틀지 않음.
Play settings. (original options = { on_complete?, restart_if_same = false })
- The default is no callback, and the same clip is not restarted.
use vanilla::{Image, Rect, SpriteAnimator, SpriteAnimatorPlayOptions};
let image = Image::create_from_pixels(64, 16, vec![0u8; 64 * 16 * 4]);
let frame_rects = [Rect::create(0.0, 0.0, 16.0, 16.0), Rect::create(16.0, 0.0, 16.0, 16.0)];
let mut animator = SpriteAnimator::new();
animator.add_clip("idle", image, &frame_rects, 10.0, true);
assert!(animator.play_clip("idle", SpriteAnimatorPlayOptions::default()));
assert!(!animator.play_clip("idle", SpriteAnimatorPlayOptions::default()));
let restart_options = SpriteAnimatorPlayOptions {
restart_if_same: true,
..SpriteAnimatorPlayOptions::default()
};
assert!(animator.play_clip("idle", restart_options));pub fn create_with_on_complete(on_complete: impl FnOnce(&mut SpriteAnimator) + 'static) -> SpriteAnimatorPlayOptions#완료 콜백만 정한 설정.
Settings with only the completion callback set.
- on_completeimpl FnOnce(&mut SpriteAnimator) + 'static
- 클립이 끝났을 때 한 번 부를 함수. 애니메이터를 받아 다음 클립을 틀 수 있다.Function to call once when the clip ends. It receives the animator and can play the next clip.
반환ReturnsSpriteAnimatorPlayOptions on_complete 를 담고 restart_if_same 이 false 인 설정.Settings holding on_complete with restart_if_same false.
클립이 끝났을 때 한 번 불린다. (반복하지 않는 클립만 끝난다)
Called once when the clip ends. (only non-looping clips end)
반환ReturnsOption<SpriteAnimatorCompleteEvent>
같은 클립이 도는 중이어도 처음부터 다시 틀지.
Whether to restart from the beginning even if the same clip is playing.
반환Returnsbool
SpriteAnimatorstruct traits Default, Component
스프라이트 애니메이터 컴포넌트.
- 같은 노드에 Sprite 를 함께 붙여 쓴다. tick 마다 지금 프레임을 그 Sprite 에 넣는다.
Sprite animator component.
- Use with a Sprite attached to the same node. Each tick puts the current frame into that Sprite.
use vanilla::{Engine, EngineConfiguration, Image, NodeTree, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};
let engine = Engine::new(EngineConfiguration::new());
let image = Image::create_from_pixels(128, 16, vec![0u8; 128 * 16 * 4]);
let idle_rects: Vec<Rect> = (0..2).map(|column| Rect::create(column as f64 * 16.0, 0.0, 16.0, 16.0)).collect();
let attack_rects: Vec<Rect> = (4..7).map(|column| Rect::create(column as f64 * 16.0, 0.0, 16.0, 16.0)).collect();
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let hero_id = node_tree.create_child(root_id, "hero");
node_tree[hero_id].add_component(Sprite::new());
let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
animator.add_clip("idle", image.clone(), &idle_rects, 10.0, true);
animator.add_clip("attack", image.clone(), &attack_rects, 12.0, false);
SpriteAnimator::play(&mut node_tree[hero_id], "attack", SpriteAnimatorPlayOptions::create_with_on_complete(|animator| {
animator.play_clip("idle", SpriteAnimatorPlayOptions::default());
}));
assert_eq!(node_tree[hero_id].get_component::<Sprite>().unwrap().get_image_rect(), Rect::create(64.0, 0.0, 16.0, 16.0));
for _ in 0..30 {
node_tree.tick(&engine, 1.0 / 60.0);
}
assert_eq!(node_tree[hero_id].get_component::<SpriteAnimator>().unwrap().get_clip_name(), Some("idle"));생성.
Constructor.
반환ReturnsSpriteAnimator 클립이 없고 틀지 않은 새 애니메이터.A new animator with no clips, not playing.
짝Counterpart: vanilla.js SpriteAnimator.constructor
클립의 기본 초당 프레임 수. (원본 fps = 10)
Default frames per second for clips. (original fps = 10)
반환Returnsf64
pub fn play(node: &mut WorldNode, clip_name: &str, options: SpriteAnimatorPlayOptions) -> bool#재생. (원본 play, 노드의 애니메이터로 틀고 같은 노드의 Sprite 에 그 자리에서 첫 프레임을 넣는다)
- 같은 클립이 이미 도는 중이면 다시 틀지 않고 완료 콜백만 바꾼다. (restart_if_same 이면 처음부터)
- 애니메이터가 없으면 false.
Play. (the original play: plays with the node's animator and puts the first frame into the Sprite on the same node right away)
- If the same clip is already playing, it does not restart and only replaces the complete callback. (from the beginning with restart_if_same)
- false if there is no animator.
- node&mut WorldNode
- SpriteAnimator 가 붙은 노드. (Sprite 가 없으면 프레임은 넣지 않고 재생만 한다)Node with a SpriteAnimator attached. (if there is no Sprite, only plays without putting in the frame)
- clip_name&str
- 틀 클립 이름.Name of the clip to play.
- optionsSpriteAnimatorPlayOptions
- 완료 콜백과 같은 클립 다시 틀기.Completion callback and restarting the same clip.
반환Returnsbool 처음부터 틀었으면 true. 없는 클립이거나 같은 클립이 도는 중이라 다시 틀지 않았거나 노드에 애니메이터가 없으면 false.true if it started from the beginning. false if the clip does not exist, the same clip is playing and was not restarted, or the node has no animator.
짝Counterpart: vanilla.js SpriteAnimator.play
같은 노드의 스프라이트 찾기. (원본 findSprite, 한 번 찾으면 기억한다)
- 원본은 찾은 Sprite 를 들고 있는다. 러스트는 형제 컴포넌트의 참조를 들 수 없어 Sprite 가 든 노드의 NodeId 를 애니메이터에 기억하고 트리에서 꺼낸다.
- tick 에서 찾았어도 기억한다. 기억한 노드에서 Sprite 를 뺐으면 None 이다.
Finds the sprite on the same node. (the original findSprite, remembers it once found)
- The original holds the Sprite it found. Rust cannot hold a reference to a sibling component, so the animator remembers the NodeId of the node holding the Sprite and takes it out of the tree.
- Also remembers it when found in tick. None if the Sprite was removed from the remembered node.
- node_tree&mut NodeTree
- 노드가 든 트리.Tree holding the node.
- node_idNodeId
- SpriteAnimator 가 붙은 노드.The node SpriteAnimator is attached to.
반환ReturnsOption<&mut Sprite> 같은 노드의 첫 Sprite. 노드가 없거나, 노드에 SpriteAnimator 나 Sprite 가 없으면 None.The first Sprite on the same node. None if the node is missing, or has no SpriteAnimator or Sprite.
짝Counterpart: vanilla.js SpriteAnimator.findSprite
use vanilla::{Image, NodeTree, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};
let image = Image::create_from_pixels(64, 16, vec![0u8; 64 * 16 * 4]);
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let hero_id = node_tree.create_child(root_id, "hero");
node_tree[hero_id].add_component(Sprite::new());
let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
animator.add_clip("run", image, &[Rect::create(16.0, 0.0, 16.0, 16.0)], 10.0, true);
SpriteAnimator::play(&mut node_tree[hero_id], "run", SpriteAnimatorPlayOptions::default());
let sprite = SpriteAnimator::find_sprite(&mut node_tree, hero_id).expect("sprite");
assert_eq!(sprite.get_image_rect(), Rect::create(16.0, 0.0, 16.0, 16.0));pub fn add_clip(&mut self, clip_name: &str, image: Rc<Image>, frame_rects: &[Rect], frame_per_second: f64, is_loop: bool)#클립 등록. (같은 이름이 있으면 바꾼다)
Registers a clip. (replaces one with the same name)
- clip_name&str
- 클립 이름. (play 에 넘길 이름)Clip name. (the name to pass to play)
- imageRc<Image>
- 프레임을 뗄 시트 이미지.Sheet image to cut frames from.
- frame_rects&[Rect]
- 시트 안의 프레임 영역 목록. (픽셀, 차례대로 넘긴다. 복사해 둔다)List of frame areas in the sheet. (pixels, advanced in order. Copied)
- frame_per_secondf64
- 초당 프레임 수. (0 이하면 넘기지 않는다, 원본 기본값은 DEFAULT_FRAME_PER_SECOND)Frames per second. (0 or less does not advance, the original default is DEFAULT_FRAME_PER_SECOND)
- is_loopbool
- true 면 반복, false 면 마지막 프레임에서 멈추고 완료 콜백을 부른다.true loops, false stops at the last frame and calls the completion callback.
짝Counterpart: vanilla.js SpriteAnimator.addClip
pub fn add_clip_from_atlas(&mut self, clip_name: &str, image: Rc<Image>, atlas_json: &serde_json::Value, frame_ids: &[&str], frame_per_second: f64, is_loop: bool)#아틀라스 JSON 으로 클립 등록. (TexturePacker 꼴 { frames: { 이름: { frame: { x, y, w, h } } } }, 없는 칸 이름은 건너뛴다)
- frame 칸이 없으면 칸 자체에서 x, y, w(width), h(height) 를 읽는다. 없는 숫자는 0 이다.
Registers a clip from atlas JSON. (TexturePacker style { frames: { name: { frame: { x, y, w, h } } } }, missing cell names are skipped)
- If there is no frame field, reads x, y, w (width), h (height) from the cell itself. Missing numbers are 0.
- clip_name&str
- 클립 이름.Clip name.
- imageRc<Image>
- 아틀라스 이미지.Atlas image.
- atlas_json&serde_json::Value
- 아틀라스 JSON 값.Atlas JSON value.
- frame_ids&[&str]
- frames 안의 칸 이름 목록. (이 차례로 프레임이 된다)List of cell names in frames. (they become frames in this order)
- frame_per_secondf64
- 초당 프레임 수.Frames per second.
- is_loopbool
- true 면 반복.true loops.
짝Counterpart: vanilla.js SpriteAnimator.addClipFromAtlas
use vanilla::{Image, SpriteAnimator, SpriteAnimatorPlayOptions};
let image = Image::create_from_pixels(64, 64, vec![0u8; 64 * 64 * 4]);
let atlas_json = serde_json::json!({
"frames": {
"run_0": { "frame": { "x": 0, "y": 0, "w": 16, "h": 20 } },
"run_1": { "frame": { "x": 16, "y": 0, "w": 16, "h": 20 } }
}
});
let mut animator = SpriteAnimator::new();
animator.add_clip_from_atlas("run", image, &atlas_json, &["run_0", "run_1"], SpriteAnimator::DEFAULT_FRAME_PER_SECOND, true);
assert!(animator.has_clip("run"));
assert!(animator.play_clip("run", SpriteAnimatorPlayOptions::default()));애니메이터만으로 재생. (처음부터 틀었으면 true)
- 같은 클립이 이미 도는 중이면 다시 틀지 않고 완료 콜백만 바꾼다. (restart_if_same 이면 처음부터)
- 노드가 없을 때(완료 콜백 안처럼) 쓴다. Sprite 에는 다음 프레임 넣기(tick, 완료 콜백 뒤의 같은 tick, apply_current_frame)에 들어간다. 노드가 있으면 그 자리에서 첫 프레임까지 넣는 SpriteAnimator::play 를 쓴다.
Play with only the animator. (true if it started from the beginning)
- If the same clip is already playing, it does not restart and only replaces the complete callback. (from the beginning with restart_if_same)
- Used when there is no node (such as inside the complete callback). The frame goes into the Sprite at the next frame update (tick, the same tick after the complete callback, apply_current_frame). With a node, use SpriteAnimator::play, which puts the first frame in right away.
- clip_name&str
- 틀 클립 이름.Name of the clip to play.
- optionsSpriteAnimatorPlayOptions
- 완료 콜백과 같은 클립 다시 틀기.Completion callback and restarting the same clip.
반환Returnsbool 처음부터 틀었으면 true. 없는 클립이거나 같은 클립이 도는 중이라 다시 틀지 않았으면 false.true if started from the beginning. false if the clip does not exist or was not restarted because the same clip is playing.
짝Counterpart: vanilla.js SpriteAnimator.playClip
정지. (첫 프레임으로 되돌리고, 완료 콜백은 부르지 않는다)
Stops. (returns to the first frame, the completion callback is not called)
짝Counterpart: vanilla.js SpriteAnimator.stop
지금 프레임을 스프라이트에 넣기. (프레임이 없으면 아무것도 하지 않는다)
Puts the current frame into a sprite. (does nothing if there is no frame)
- sprite&mut Sprite
- 이미지와 이미지 영역을 넣을 스프라이트.Sprite to put the image and image area into.
짝Counterpart: vanilla.js SpriteAnimator.applyCurrentFrame
use vanilla::{Image, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};
let image = Image::create_from_pixels(32, 16, vec![0u8; 32 * 16 * 4]);
let mut animator = SpriteAnimator::new();
animator.add_clip("blink", image, &[Rect::create(16.0, 0.0, 16.0, 16.0)], 10.0, true);
animator.play_clip("blink", SpriteAnimatorPlayOptions::default());
let mut sprite = Sprite::new();
animator.apply_current_frame(&mut sprite);
assert_eq!(sprite.get_image_rect(), Rect::create(16.0, 0.0, 16.0, 16.0));지금 클립 이름 반환. (아직 틀지 않았으면 None)
Returns the current clip name. (None if not played yet)
반환ReturnsOption<&str> 마지막으로 처음부터 튼 클립 이름. 아직 틀지 않았으면 None. (stop 해도 남는다)Name of the clip last started from the beginning. None if not played yet. (remains after stop)
짝Counterpart: vanilla.js SpriteAnimator.getClipName
재생 중인지.
Whether it is playing.
반환Returnsbool 프레임을 넘기는 중이면 true. 반복하지 않는 클립이 끝났거나 stop 했으면 false.true while advancing frames. false if a non-looping clip has ended or stop was called.
짝Counterpart: vanilla.js SpriteAnimator.isPlaying
클립이 있는지.
Whether a clip exists.
- clip_name&str
- 찾을 클립 이름.Name of the clip to look up.
반환Returnsbool 그 이름으로 등록한 클립이 있으면 true.true if a clip is registered under that name.
짝Counterpart: vanilla.js SpriteAnimator.hasClip
지금 프레임 번호.
Current frame index.
반환Returnsusize 지금 클립 안의 프레임 번호. (0 부터)Frame index within the current clip. (from 0)
짝Counterpart: vanilla.js SpriteAnimator.getCurrentFrameIndex