Advertisement
jotaFelipe

2D Sprite Animation Script

Jan 3rd, 2014
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class animationControlScript : MonoBehaviour {
  5.    
  6.     private int frameAmount;
  7.     private int animAmount;
  8.     private float animCurrentFrame;
  9.     private  float frameReader = 0f;
  10.     private int lastPlayedId = 0;
  11.    
  12.     public void animate (GameObject GO, int frameSizePixels, int animId, int realNumberOfFrames, int frameRate) {
  13.        
  14.         //get number of frames
  15.         frameAmount = (GO.renderer.material.mainTexture.width / frameSizePixels);
  16.         //get number of animations
  17.         animAmount = (GO.renderer.material.mainTexture.height / frameSizePixels);
  18.        
  19.         //reset frame reader if playing a new animation
  20.         if (lastPlayedId != animId) {
  21.             frameReader = 0f;
  22.         }
  23.        
  24.         //texture tiling - scale texture to fit number of animations
  25.         GO.renderer.material.mainTextureScale = new Vector2(1.0f / frameAmount, 1.0f / animAmount);
  26.         //frame reading
  27.         GO.renderer.material.mainTextureOffset = new Vector2(frameReader, (1.0f * (animAmount - animId) / animAmount));
  28.        
  29.         //move frame reader to next frame by the frame rate selected
  30.         if (Time.fixedTime - animCurrentFrame >= (frameRate * 1.0f) / 30.0f ) {
  31.             animCurrentFrame = Time.fixedTime;
  32.             frameReader += 1.0f/frameAmount;
  33.            
  34.             //if the frame reader is past the existing frame number, return to frame 1         
  35.             if (frameReader >= realNumberOfFrames * 1.0f / frameAmount * 1.0f) {
  36.                 frameReader = 0f;
  37.             }
  38.         }
  39.         lastPlayedId = animId;
  40.        
  41.     }//animate end
  42.    
  43.    
  44.    
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement