Source

ArduinoProjects / Libraries / Animation / Animation.cpp

#include "Animation.h"
#include "MathTypes.h"
#include "MathUtil.h"

  Animation::Animation(KeyFrame* valueArray, int numValues, AnimMode mode)
  {
    animDir = 1.0f;
	totalAnimTime = valueArray[numValues-1].time;
    currT = 0.0f;
    animSpeed = 1.0f;
    numAnimValues = MAX_NUM_ANIM_VALUES;
    animMode = mode;
	endPauseTime = 0.0f;
	pauseTimer = 0.0f;
    
    SetValues(valueArray,numValues);
  }

  float Animation::CalcAnimVal()
  {
	if(currT >= totalAnimTime)
	{
		return animValues[numAnimValues-1].value;
	}
	  
	KeyFrame* pStartFrame = 0;
	KeyFrame* pEndFrame = 0;
	  
	for(int i=0; i<numAnimValues-1; ++i)
	{
		KeyFrame* pCurrFrame = &animValues[i];
		if(pCurrFrame->time < currT)
		{
			pStartFrame = pCurrFrame;
			pEndFrame = &animValues[i+1];
		}
	}
	  
	if(pStartFrame == 0
	   || pEndFrame == 0)
	{
		return 0.0f;
	}

	const float startTime = pStartFrame->time;
	const float endTime = pEndFrame->time;
	const float lerpT = (currT - startTime)/(endTime-startTime);
	
	const float animVal = Lerp(pStartFrame->value,pEndFrame->value,lerpT);
	  
	return animVal;
  }

  void Animation::SetValues(KeyFrame* valueArray, int numValues)
  {
    //Safety check
    if(numValues > MAX_NUM_ANIM_VALUES)
    {
      return;
    }
    
    for(int i=0; i<numValues; ++i)
    {
      animValues[i] = valueArray[i];
    }
    
    numAnimValues = numValues;
  }
  
  void Animation::Update(float timeDelta)
  {
	if(pauseTimer > 0.0f)
	{
		pauseTimer -= animSpeed*timeDelta;
		return;
	}
	  
    switch(animMode)
    {
      case AnimMode_Wrap:
      {
        currT += animSpeed*timeDelta;
    
        if(currT >= totalAnimTime)
        {
          currT -= totalAnimTime;
			
		  pauseTimer += endPauseTime;
        }
        
        break;
      }
      case AnimMode_PingPong:
      {
        currT += animSpeed*animDir*timeDelta;
        
        if(currT >= totalAnimTime)
        {
		  currT = totalAnimTime - (currT - totalAnimTime);
          animDir = -1.0f;
			
          pauseTimer += endPauseTime;
        }
        else if(currT <= 0.0f)
        {
          currT = -currT;
          animDir = 1.0f;
        }
        
        break;
      }
    }
  }