Howdy all. I am currently making a 2D game that utilizes sprites and spritesheets. The animations in the game are meant to run at 12 fps (to maintain a retro/vintage style). However, I am not sure what the best practice is to implement this. My current solution is utilizing Application.targetFrameRate = 12 to limit the game’s framerate to 12, but I’m not sure this is the best practice to follow. While this method works nicely for all Unity animations, spritesheets are hit or miss. I have tried setting the spritesheets’ animators to 12 samples, but I can clearly see that some frames are getting skipped. I know that there are plenty of games that utilize low FPS animations, so I’m certain there is a solution, I just don’t know what it is. Any assistance would be much appreciated. Thanks!
You can use the regular Update loop or a coroutine with Time.deltaTime to do this.
Something like this:
using System.Collections;
using UnityEngine;
public class SpriteAnimator : MonoBehaviour
{
public SpriteRenderer spriteRenderer;
public Sprite[] frames;
public float fps = 12f;
public bool loop = true;
public bool playOnStart = true;
public bool IsPlaying { get; set; }
private float animationTime;
private void Start()
{
if (playOnStart) Play();
}
public void Play()
{
if (IsPlaying) return;
StartCoroutine(PlayAnimation());
}
public void Stop()
{
IsPlaying = false;
}
IEnumerator PlayAnimation()
{
IsPlaying = true;
int numFrames = frames.Length;
animationTime = 0f;
spriteRenderer.sprite = frames[0];
yield return null; //allow first frame to be displayed
while (IsPlaying)
{
animationTime += Time.deltaTime * fps;
int nextFrame;
if (loop)
{
nextFrame = (int)animationTime % numFrames;
}
else
{
nextFrame = (int)animationTime;
if (nextFrame > numFrames - 1)
{
nextFrame = numFrames - 1;
IsPlaying = false;
}
}
spriteRenderer.sprite = frames[nextFrame];
yield return null;
}
}
}