Skip to content

Instantly share code, notes, and snippets.

@Xenakios
Created January 6, 2023 16:50
Show Gist options
  • Select an option

  • Save Xenakios/302893019b697cd2a47fc3a62589a918 to your computer and use it in GitHub Desktop.

Select an option

Save Xenakios/302893019b697cd2a47fc3a62589a918 to your computer and use it in GitHub Desktop.
class Animator : public Timer
{
public:
enum class State
{
Started,
Running,
Finished
};
Animator(int updateinterval = 40) : m_update_interval(updateinterval)
{
CurveFunc = [](double x){ return x; }; // by default, just a linear mapping
}
using animfunc = std::function<void(State, double)>;
// CurveFunc is given a value between 0.0-1.0 and must return a value between 0.0-1.0
std::function<double(double)> CurveFunc;
void timerCallback() override
{
double elapsed = Time::getMillisecondCounterHiRes()-m_starttime;
double normpos = 1.0 / m_dur * elapsed;
if (m_cb)
{
if (normpos >= 1.0)
{
m_cb(State::Finished, CurveFunc(1.0));
stopTimer();
}
else
m_cb(State::Running, CurveFunc(normpos));
}
}
void start(double duration,animfunc f)
{
m_cb = f;
m_dur = jlimit(0.1, 600.0, duration)*1000.0;
m_starttime = Time::getMillisecondCounterHiRes();
if (m_cb)
m_cb(State::Started, CurveFunc(0.0));
startTimer(m_update_interval);
}
void stop()
{
stopTimer();
if (m_cb)
m_cb(State::Finished, CurveFunc(1.0));
}
private:
animfunc m_cb;
double m_starttime = 0.0;
double m_dur = 0.1;
int m_update_interval = 40;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment