Advertisement
infinite_ammo

SpriteAnimator.cs

Feb 20th, 2014
4,145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.58 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SpriteAnimator : MonoBehaviour
  5. {
  6.     [System.Serializable]
  7.     public class AnimationTrigger
  8.     {
  9.         public string name;
  10.         public int frame;
  11.     }
  12.  
  13.     [System.Serializable]
  14.     public class Animation
  15.     {
  16.         public string name;
  17.         public int fps;
  18.         public Sprite[] frames;
  19.  
  20.         public string sequenceCode;
  21.         public string cue;
  22.  
  23.         public AnimationTrigger[] triggers;
  24.     }
  25.  
  26.     // sequence code format:
  27.     // startFrame-endFrame:time(chance)
  28.     // time: also be set to "forever" - this will loop the sequence indefinitely
  29.     // chance: float value from 0-1, chance that the sequence will play (if not played, it will be skipped)
  30.     // time and chance can both be ignored, this will mean the sequence plays through once
  31.  
  32.     // sequence code examples:
  33.     // TV: 0-1:3, 2-3:3, 4-5:4, 6-7:4, 8:3, 9:3
  34.     // Idle animation with random fidgets: 0-59, 60-69, 10-59, 0-59(.25), 70-129(.75)
  35.     // Jump animation with looping finish: 0-33, 20-33:forever
  36.  
  37.     public SpriteRenderer spriteRenderer;
  38.     public Animation[] animations;
  39.  
  40.     public bool playing { get; private set; }
  41.     public Animation currentAnimation { get; private set; }
  42.     public int currentFrame { get; private set; }
  43.     [HideInInspector]
  44.     public bool loop;
  45.     public float speedMultiplier = 1f;
  46.  
  47.     public string playAnimationOnStart;
  48.  
  49.     bool looped;
  50.  
  51.     void Start()
  52.     {
  53.         if (!spriteRenderer)
  54.             spriteRenderer = GetComponent<SpriteRenderer>();
  55.  
  56.         if (playAnimationOnStart != "")
  57.             Play(playAnimationOnStart);
  58.     }
  59.    
  60.     void OnDisable()
  61.     {
  62.         playing = false;
  63.         currentAnimation = null;
  64.     }
  65.  
  66.     public void Play(string name, bool loop = true, int startFrame = 0)
  67.     {
  68.         Animation animation = GetAnimation(name);
  69.         if (animation != null )
  70.         {
  71.             if (animation != currentAnimation)
  72.             {
  73.                 ForcePlay(name, loop, startFrame);
  74.             }
  75.         }
  76.         else
  77.         {
  78.             Debug.LogWarning("could not find animation: " + name);
  79.         }
  80.     }
  81.  
  82.     public void ForcePlay(string name, bool loop = true, int startFrame = 0)
  83.     {
  84.         Animation animation = GetAnimation(name);
  85.         if (animation != null)
  86.         {
  87.             this.loop = loop;
  88.             currentAnimation = animation;
  89.             playing = true;
  90.             currentFrame = startFrame;
  91.             spriteRenderer.sprite = animation.frames[currentFrame];
  92.             StopAllCoroutines();
  93.             StartCoroutine(PlayAnimation(currentAnimation));
  94.         }
  95.         else
  96.         {
  97.             Debug.LogWarning("Could not find animation: " + name);
  98.         }
  99.     }
  100.  
  101.     public void SlipPlay(string name, int wantFrame, params string[] otherNames)
  102.     {
  103.         for (int i = 0; i < otherNames.Length; i++)
  104.         {
  105.             if (currentAnimation != null && currentAnimation.name == otherNames[i])
  106.             {
  107.                 Play(name, true, currentFrame);
  108.                 break;
  109.             }
  110.         }
  111.         Play(name, true, wantFrame);
  112.     }
  113.  
  114.     public bool IsPlaying(string name)
  115.     {
  116.         return (currentAnimation != null && currentAnimation.name == name);
  117.     }
  118.  
  119.     public Animation GetAnimation(string name)
  120.     {
  121.         foreach (Animation animation in animations)
  122.         {
  123.             if (animation.name == name)
  124.             {
  125.                 return animation;
  126.             }
  127.         }
  128.         return null;
  129.     }
  130.  
  131.     IEnumerator CueAnimation(string animationName, float minTime, float maxTime)
  132.     {
  133.         yield return new WaitForSeconds(Random.Range(minTime, maxTime));
  134.         ForcePlay(animationName, false);
  135.     }
  136.  
  137.     IEnumerator PlayAnimation(Animation animation)
  138.     {
  139.         playing = true;
  140.  
  141.         speedMultiplier = 1f;
  142.         //Debug.Log("Playing animation: " + animation.name);
  143.  
  144.         float timer = 0f;
  145.         float delay = 1f / (float)animation.fps;
  146.         string cueOnComplete = "";
  147.  
  148.         if (animation.cue != null && animation.cue != "")
  149.         {
  150.             if (animation.cue.IndexOf(':') != -1)
  151.             {
  152.                 string[] dataBits = animation.cue.Trim().Split(':');
  153.  
  154.                 string animationName = dataBits[1];
  155.                 dataBits = dataBits[0].Split('-');
  156.                
  157.                 float minTime = float.Parse(dataBits[0], System.Globalization.CultureInfo.InvariantCulture);
  158.                 float maxTime = minTime;
  159.                
  160.                 if (dataBits.Length > 1)
  161.                     maxTime = float.Parse(dataBits[1], System.Globalization.CultureInfo.InvariantCulture);
  162.                
  163.                 StartCoroutine(CueAnimation(animationName, minTime, maxTime));
  164.  
  165.                 loop = true;
  166.             }
  167.             else
  168.             {
  169.                 cueOnComplete = animation.cue.Trim();
  170.             }
  171.         }
  172.  
  173.         if (animation.sequenceCode != null && animation.sequenceCode != "")
  174.         {
  175.             while (true)
  176.             {
  177.                 string[] split = animation.sequenceCode.Split(',');
  178.                 for (int i = 0; i < split.Length; i++)
  179.                 {
  180.                     string data = split[i].Substring(0, split[i].Length);
  181.                     float duration = 0f;
  182.                     float chance = 1f;
  183.                     string[] dataBits;
  184.  
  185.                     if (data.IndexOf('(') != -1)
  186.                     {
  187.                         int startIndex = data.IndexOf('(');
  188.                         int endIndex = data.IndexOf(')');
  189.                         string chanceString = data.Substring(startIndex+1, endIndex - (startIndex+1));
  190.                         chance = float.Parse(chanceString, System.Globalization.CultureInfo.InvariantCulture);
  191.                         data = data.Substring(0, startIndex);
  192.                     }
  193.  
  194.                     if (Random.value > chance)
  195.                         continue;
  196.  
  197.                     bool readFrames = true;
  198.  
  199.                     if (data.IndexOf(':') != -1)
  200.                     {
  201.                         dataBits = data.Trim().Split(':');
  202.                         if (dataBits[0] == "fps")
  203.                         {
  204.                             readFrames = false;
  205.                         }
  206.                         else if (dataBits[0] == "goto")
  207.                         {
  208.                             readFrames = false;
  209.                         }
  210.                         else if (dataBits[0] == "label")
  211.                         {
  212.                             readFrames = false;
  213.                         }
  214.                         else
  215.                         {
  216.                             if (dataBits.Length > 1)
  217.                             {
  218.                                 if (dataBits[1] == "forever")
  219.                                     duration = -1f;
  220.                                 else
  221.                                     duration = float.Parse(dataBits[1], System.Globalization.CultureInfo.InvariantCulture);
  222.                             }
  223.  
  224.                             dataBits = dataBits[0].Split('-');
  225.                         }
  226.                     }
  227.                     else
  228.                     {
  229.                         dataBits = data.Trim().Split('-');
  230.                     }
  231.  
  232.                     if (readFrames)
  233.                     {
  234.                         int startFrame = -1;
  235.                         int endFrame = -1;
  236.  
  237.                         startFrame = int.Parse(dataBits[0], System.Globalization.CultureInfo.InvariantCulture);
  238.                         endFrame = startFrame;
  239.  
  240.                         if (dataBits.Length > 1)
  241.                             endFrame = int.Parse(dataBits[1], System.Globalization.CultureInfo.InvariantCulture);
  242.  
  243.                         currentFrame = startFrame;
  244.  
  245.                         //Debug.Log ("startFrame: " + startFrame + " endFrame: " + endFrame + " duration: " + duration);
  246.  
  247.                         if (duration <= 0f)
  248.                         {
  249.                             while (duration < 0f || currentFrame < endFrame)
  250.                             {
  251.                                 while (timer < delay)
  252.                                 {
  253.                                     timer += Time.deltaTime * speedMultiplier;
  254.                                     yield return null;
  255.                                 }
  256.                                
  257.                                 while (timer >= delay)
  258.                                 {
  259.                                     timer -= delay;
  260.                                     NextFrame(animation);
  261.                                 }
  262.                                
  263.                                 spriteRenderer.sprite = animation.frames[currentFrame];
  264.                             }
  265.                         }
  266.                         else
  267.                         {
  268.                             while (duration > 0f)
  269.                             {
  270.                                 while (timer < delay)
  271.                                 {
  272.                                     duration -= Time.deltaTime * speedMultiplier;
  273.                                     timer += Time.deltaTime * speedMultiplier;
  274.                                     yield return null;
  275.                                 }
  276.                                 while (timer >= delay)
  277.                                 {
  278.                                     timer -= delay;
  279.                                     currentFrame++;
  280.                                     if (currentFrame > endFrame)
  281.                                         currentFrame = startFrame;
  282.                                 }
  283.  
  284.                                 spriteRenderer.sprite = animation.frames[currentFrame];
  285.                             }
  286.                         }
  287.                     }
  288.                 }
  289.                 //Debug.LogWarning("cueOnComplete: " + cueOnComplete);
  290.                 if (cueOnComplete != "")
  291.                     ForcePlay(cueOnComplete, loop);
  292.             }
  293.         }
  294.         else
  295.         {
  296.             while (loop || currentFrame < animation.frames.Length-1)
  297.             {
  298.                 while (timer < delay)
  299.                 {
  300.                     timer += Time.deltaTime * speedMultiplier;
  301.                     yield return null;
  302.                 }
  303.  
  304.                 while (timer >= delay)
  305.                 {
  306.                     timer -= delay;
  307.                     NextFrame(animation);
  308.                 }
  309.  
  310.                 spriteRenderer.sprite = animation.frames[currentFrame];
  311.             }
  312.             if (cueOnComplete != "")
  313.                 ForcePlay(cueOnComplete, loop);
  314.         }
  315.  
  316.         currentAnimation = null;
  317.         playing = false;
  318.     }
  319.  
  320.     void NextFrame(Animation animation)
  321.     {
  322.         looped = false;
  323.         currentFrame++;
  324.         foreach (AnimationTrigger animationTrigger in animation.triggers)
  325.         {
  326.             if (animationTrigger.frame == currentFrame)
  327.             {
  328.                 gameObject.SendMessageUpwards(animationTrigger.name);
  329.             }
  330.         }
  331.  
  332.         if (currentFrame >= animation.frames.Length)
  333.         {
  334.             if (loop)
  335.                 currentFrame = 0;
  336.             else
  337.                 currentFrame = animation.frames.Length - 1;
  338.         }
  339.     }
  340.  
  341.     public int GetFacing()
  342.     {
  343.         return (int)Mathf.Sign(spriteRenderer.transform.localScale.x);
  344.     }
  345.  
  346.     public void FlipTo(float dir)
  347.     {
  348.         if (dir < 0f)
  349.             spriteRenderer.transform.localScale = new Vector3(-1f, 1f, 1f);
  350.         else
  351.             spriteRenderer.transform.localScale = new Vector3(1f, 1f, 1f);
  352.     }
  353.  
  354.     public void FlipTo(Vector3 position)
  355.     {
  356.         float diff = position.x - transform.position.x;
  357.         if (diff < 0f)
  358.             spriteRenderer.transform.localScale = new Vector3(-1f, 1f, 1f);
  359.         else
  360.             spriteRenderer.transform.localScale = new Vector3(1f, 1f, 1f);
  361.     }
  362. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement