Skip to content

Instantly share code, notes, and snippets.

@kidapu
Created May 14, 2016 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kidapu/b7e2f0f836b0a3839c15232a928f246f to your computer and use it in GitHub Desktop.
Save kidapu/b7e2f0f836b0a3839c15232a928f246f to your computer and use it in GitHub Desktop.
C++11_openframeworks_tween_util_class
#include "ofMain.h"
class Utils
{
public:
static void tween(float start_val, float end_val, int interval, std::function<void(float)> task, std::function<void()> complete = [](){})
{
auto start_time = std::chrono::system_clock::now();
std::thread([start_val, end_val, interval, start_time, task, complete]() {
while(true)
{
auto end_time = std::chrono::system_clock::now() ;
auto elapsed = std::chrono::duration_cast< std::chrono::milliseconds >( end_time - start_time);
if( interval <= elapsed.count() )
{
task(end_val);
complete();
break;
}
float tt = start_val + (end_val - start_val) * elapsed.count() / interval;
task(tt);
std::this_thread::sleep_for(std::chrono::milliseconds(1000/30));
}
}).detach();
}
static void later(int interval, bool async, std::function<void()> task)
{
if (async)
{
std::thread([interval, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
task();
}).detach();
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
task();
}
}
};
class ofApp : public ofBaseApp
{
public:
int _hue = 0;
void setup()
{
ofSetColor(255);
ofBackground(0);
ofSetCircleResolution(50);
}
void draw()
{
ofSetColor( ofColor::fromHsb( _hue, 255, 255 ) );
ofDrawCircle(ofGetWidth()*0.5, ofGetHeight()*0.5, sin(ofGetElapsedTimeMillis()*0.005)*100.0);
}
void keyPressed(int key)
{
switch(key)
{
case '1':
{
Utils::tween(0, 255, 2000, [&](float val){
_hue = val ;
cout << "tween hue:" << _hue << endl;
});
break;
}
case '2':
{
Utils::tween(0, 255, 2000, [&](float val){
_hue = val ;
cout << "tween hue:" << _hue << endl;
}, [&](){
_hue = 100;
cout << "end tween" << endl;
});
break;
}
case '3':
{
Utils::later(1000, true, [&](){
_hue += 30;
cout << "later:" << _hue << endl;
});
break;
}
}
}
};
int main( )
{
ofSetupOpenGL(500,500,OF_WINDOW);
ofRunApp(new ofApp());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment