using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class SpriteAnimator : MonoBehaviour
{
private SpriteRenderer spriteRenderer;
[SerializeField]
private Sprite idleSprite;
[SerializeField]
private Sprite[] moveUpSprites;
[SerializeField]
private Sprite[] moveDownSprites;
[SerializeField]
private Sprite[] moveLeftSprites;
[SerializeField]
private Sprite[] moveRightSprites;
private Vector2 lastDirection;
[HideInInspector]
public Vector2 direction;
private int currentSpriteIndex = 0;
private float timePlayedForCurrentSpriteFrame;
[SerializeField]
private float timeFor1Frame = 0.5f;
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
void Start()
{
TypeSingleton.Get<PlayerController>().OnDirectionChanged += SetDirection;
spriteRenderer.sprite = idleSprite;
}
// Update is called once per frame
void Update()
{
if (direction.Equals(Vector2.zero)) PlayIdle();
else if(direction.Equals(Vector2.up)) PlayMove(moveUpSprites);
else if(direction.Equals(Vector2.down)) PlayMove(moveDownSprites);
else if(direction.Equals(Vector2.left)) PlayMove(moveLeftSprites);
else if (direction.Equals(Vector2.right)) PlayMove(moveRightSprites);
lastDirection = direction;
}
private void PlayMove(Sprite[] spritesList)
{
if (timePlayedForCurrentSpriteFrame >= timeFor1Frame)
{
timePlayedForCurrentSpriteFrame = 0;
currentSpriteIndex++;
if(currentSpriteIndex == spritesList.Length)
currentSpriteIndex = 0;
}
spriteRenderer.sprite = spritesList[currentSpriteIndex];
timePlayedForCurrentSpriteFrame += Time.deltaTime;
}
private void PlayIdle()
{
if (lastDirection.Equals(Vector2.up)) spriteRenderer.sprite = moveUpSprites[0];
else if (lastDirection.Equals(Vector2.down)) spriteRenderer.sprite = moveDownSprites[0];
else if (lastDirection.Equals(Vector2.left)) spriteRenderer.sprite = moveLeftSprites[0];
else if (lastDirection.Equals(Vector2.right)) spriteRenderer.sprite = moveRightSprites[0];
}
public void SetDirection(Vector2 direction)
{
this.direction = direction;
if(lastDirection != direction)
currentSpriteIndex = 0;
}
}