using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BF { public class MultipleSpriteAnimation : MonoBehaviour { List spriteList; private int spriteCount = 0; private bool IsPlayAnimation = false; private SpriteRenderer spriteRenderer; private int currIndex = 0; private int startIndex = 0; private int endIndex = 0; private int animationCount = 0; private float interval = 0.05f; private float time = 0.0f; private float currAnimationTime = 0.0f; private bool isLoop = false; private bool isEnd = false; private bool isInit = false; void Awake() { spriteRenderer = GetComponent(); } public void SetSpriteList(SimpleAtlas atlas) { spriteList = atlas.GetSpriteList(); spriteCount = spriteList.Count; if (!ReferenceEquals(spriteRenderer, null)) { isInit = true; } } public void PlayAnimation(int startIndex, int endIndex, bool isLoop, float interval = 0.05f) { if(IsPlayAnimation && this.startIndex == startIndex && this.endIndex == endIndex && this.isLoop == isLoop) { return; } this.startIndex = startIndex; this.currIndex = startIndex; this.endIndex = endIndex; this.isLoop = isLoop; this.isEnd = false; this.IsPlayAnimation = true; this.animationCount = endIndex - startIndex + 1; this.time = 0.0f; this.currAnimationTime = 0.0f; this.interval = interval; } public void PlayAnimation(bool isLoop, float interval = 0.05f) { if(IsPlayAnimation && this.startIndex == 0 && this.endIndex == spriteCount - 1 && this.isLoop == isLoop) { return; } this.startIndex = 0; this.currIndex = 0; this.endIndex = spriteCount - 1; this.isLoop = isLoop; this.isEnd = false; this.IsPlayAnimation = true; this.animationCount = spriteCount; this.time = 0.0f; this.currAnimationTime = 0.0f; this.interval = interval; } public void SetOder(int order) { if (!ReferenceEquals(spriteRenderer, null)) { spriteRenderer.sortingOrder = order; } } void Update() { if (!isInit) { return; } if (!IsPlayAnimation) { return; } time += Time.deltaTime; var index = Mathf.FloorToInt(time / interval); if (index <= 0) { return; } if (isLoop) { currIndex += index; if (currIndex > endIndex) { currIndex = startIndex + (currIndex - startIndex) % animationCount; } } else { currIndex += index; if (currIndex > endIndex) { currIndex = endIndex; isEnd = true; IsPlayAnimation = false; } } time = time - interval*index; spriteRenderer.sprite = spriteList[currIndex]; } } }