using System;
using UnityEngine;

namespace FramedAnimator {
	[RequireComponent(typeof(SpriteRenderer))]
	public class FramedAnimator : MonoBehaviour {
		[SerializeField] private Sprite[] sprites;
		[SerializeField] private float frameRate;

		private float _currentFrame;
		private int _renderingFrame;
		private int _limit;

		private SpriteRenderer _renderer;

		private void Awake() {
			_renderer = GetComponent<SpriteRenderer>();
		}

		private void Update() {
			if (_renderingFrame >= _limit)
				return;
			_currentFrame += Time.deltaTime * frameRate;

			_renderingFrame = Mathf.Clamp(Mathf.FloorToInt(_currentFrame), 0, _limit);
			_renderer.sprite = sprites[_renderingFrame];
		}

		public void PlayUntil(float fraction) {
			_limit = Mathf.RoundToInt(sprites.Length * Mathf.Clamp(fraction, 0, 1));
			_limit = Mathf.Clamp(_limit, 0, sprites.Length - 1);
		}
	}
}