Created
February 2, 2015 07:14
-
-
Save nariakiiwatani/92651e5d618ebdc2a235 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include "ofEventUtils.h" | |
#include "ofEvents.h" | |
#include "ofAppRunner.h" | |
template<typename T> | |
class Animation | |
{ | |
public: | |
Animation():ptr_(&value_){} | |
Animation(T &t):ptr_(&t){} | |
~Animation() { if(animating_) removeListener(); } | |
operator const T&() { return *ptr_; } | |
bool isEnd() { return !animating_; } | |
void to(T v, float time) { | |
from_ = *ptr_; | |
to_ = v; | |
time_ = time; | |
elapsed_ = 0; | |
if(!animating_) { | |
animating_ = true; | |
addListener(); | |
} | |
} | |
void stop() { | |
if(animating_) { | |
animating_ = false; | |
removeListener(); | |
} | |
} | |
void set(const T &t) { *ptr_ = t; stop(); } | |
void setReference(T &t) { ptr_ = &t; } | |
protected: | |
virtual T interpolate(const T &from, const T &to, float ratio) { | |
return from*(1-ratio) + to*ratio; | |
} | |
private: | |
void addListener() { ofAddListener(ofEvents().update, this, &Animation::update); } | |
void removeListener() { ofRemoveListener(ofEvents().update, this, &Animation::update); } | |
void update(ofEventArgs &arg) { | |
elapsed_ += ofGetLastFrameTime(); | |
float time_ratio = elapsed_/time_; | |
if(time_ratio >= 1) { | |
*ptr_ = to_; | |
stop(); | |
} | |
else { | |
*ptr_ = interpolate(from_, to_, time_ratio); | |
} | |
} | |
T value_, from_, to_, *ptr_; | |
float time_, elapsed_; | |
bool animating_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment