WXMC/proj/unity/Assets/Scripts/Animation/SpriteSequencePlayer.cs
2024-12-20 16:08:29 +08:00

93 lines
2.3 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class SpriteSequencePlayer : MonoBehaviour
{
// Array of sprites to animate
public Sprite[] Sprites;
// Speed of the animation in frames per second
[Range(1, 60)]
public int FramesPerSecond = 10;
// Whether the animation should loop
public bool Loop = true;
// SpriteRenderer to apply the animation to
private SpriteRenderer m_spriteRenderer;
// Timer to track the current frame
private float m_timer;
// Current frame index
private int m_currentFrame;
void Start()
{
// Get the SpriteRenderer component on this GameObject
m_spriteRenderer = GetComponent<SpriteRenderer>();
// Ensure we have sprites to animate
if (Sprites == null || Sprites.Length == 0)
{
Debug.LogWarning("No sprites assigned to the animator.");
}
}
void Update()
{
if (Sprites == null || Sprites.Length == 0)
{
return;
}
if (!Loop && m_currentFrame >= Sprites.Length)
{
return;
}
// Calculate the time for each frame based on the animation speed
float frameDuration = 1f / FramesPerSecond;
// Increment the timer by the time elapsed since the last frame
m_timer += Time.deltaTime;
// If the timer exceeds the frame duration, update the frame
if (m_timer >= frameDuration)
{
m_timer -= frameDuration;
// Increment the frame index
m_currentFrame++;
// Check if we reached the end of the sprite array
if (m_currentFrame >= Sprites.Length)
{
if (Loop)
{
m_currentFrame = 0; // Loop back to the first frame
}
else
{
//m_currentFrame = -1;
}
}
Sprite sprite;
if (m_currentFrame < 0 || m_currentFrame >= Sprites.Length)
{
sprite = null;
}
else
{
sprite = Sprites[m_currentFrame];
}
// Update the sprite on the SpriteRenderer
m_spriteRenderer.sprite = sprite;
}
}
}