BerkinAkkaya

Animation Curves with Unity

Nov 25th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.06 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class Animate : MonoBehaviour {
  4.  
  5.     //MY BLOG: berkinakkaya.wixsite.com/blog
  6.  
  7.     AnimationCurve curve;
  8.  
  9.     [Header("Visual Settings")]
  10.     [SerializeField] float heightMultiplier = 2f;
  11.     [SerializeField] float acceleration = 5f;
  12.     [SerializeField] float maxSpeed = 20f;
  13.     [SerializeField] float curveLength;
  14.     [SerializeField] bool startWithDelay;
  15.  
  16.     [Header("Colors")]
  17.     [SerializeField] Color cold;
  18.     [SerializeField] Color hot;
  19.  
  20.     float speed;
  21.     SpriteRenderer sprite;
  22.  
  23.     void Start()
  24.     {
  25.         sprite = GetComponent<SpriteRenderer>();
  26.         CreateCurve();
  27.     }
  28.  
  29.     public void CreateCurve()
  30.     {
  31.         curve = new AnimationCurve(); //Construct the curve
  32.  
  33.         //Set Wrap Modes
  34.         curve.preWrapMode = WrapMode.Loop;
  35.         curve.postWrapMode = WrapMode.Loop;
  36.  
  37.         //Clear the curve
  38.         for(int i = 0; i < curve.length; i++)
  39.         {
  40.             curve.RemoveKey(i);
  41.         }
  42.        
  43.         Keyframe[] keys = new Keyframe[3];
  44.  
  45.         if(startWithDelay)
  46.         {
  47.             keys[0] = new Keyframe(0.5f              , 0);
  48.             keys[1] = new Keyframe(0.5f+curveLength/2, 1);
  49.             keys[2] = new Keyframe(0.5f+curveLength  , 0);
  50.         }
  51.         else
  52.         {
  53.             keys[0] = new Keyframe(0            , 0);
  54.             keys[1] = new Keyframe(curveLength/2, 1);
  55.             keys[2] = new Keyframe(curveLength  , 0);
  56.         }
  57.  
  58.         curve.keys = keys;
  59.     }
  60.  
  61.     void Update()
  62.     {
  63.         CalculateSpeed();
  64.  
  65.         float value = curve.Evaluate(Value());
  66.         Scale(value);
  67.         UpdateColor(value);
  68.     }
  69.  
  70.     void UpdateColor(float value)
  71.     {
  72.         Color color = Color.Lerp(cold, hot, value);
  73.         sprite.color = color;
  74.     }
  75.  
  76.     void Scale(float height)
  77.     {
  78.         transform.localScale = Vector3.one + Vector3.up * height * heightMultiplier;
  79.     }
  80.  
  81.     void CalculateSpeed()
  82.     {
  83.         if(speed < maxSpeed)
  84.             speed += (acceleration * Time.deltaTime);
  85.  
  86.         speed = Mathf.Clamp(speed, 0, maxSpeed);
  87.     }
  88.  
  89.     float Value()
  90.     {
  91.         return (Time.time * speed) % curveLength;
  92.     }
  93. }
Add Comment
Please, Sign In to add comment