openFrameworks 基本動作 超基本編

今月末のiPhoneの勉強会に備えて、昨年7月以来、久々にopenFrameworksをやろうと本を引っぱり出してきました。

Beyond Interaction ―メディアアートのためのopenFrameworksプログラミング入門

まずは超基本な所からまとめていきます。

直線を書く

まず直線を引く。 [cpp] void testApp::draw(){

  ofLine(100,200,500,900);

} [/cpp]

ofLine()という関数を利用します。 引数は、左から<出発点のx座標>、<出発点のy座標>、<終点のx座標>、<終点のy座標> です。

四角形、円、三角形を書く

四角形 [cpp] void testApp::draw(){

  ofRect(100,100,200,300);

} [/cpp]

円 [cpp] void testApp::draw(){

 ofCircle(400,400,80);

 ofEllipse(800,100,80,30);

}

[/cpp]

楕円を書く際には、ofEllipse()を利用する。

三角形 [cpp] void testApp::draw(){

  ofTriangle(700,200,300,300,800,70);

}

[/cpp]

色の設定

背景と実際に描画される絵の色を決める。

[cpp] //背景 ofBackground(255,255,255);

//描画の色 ofSetColor(124,123,124); ofCircle(200,200,80);

[/cpp]

色はRGBで指定する。

透明度を設定する

透明度を設定するために、ofEnableAlphaBlending()を使う。 後は色の設定の際に、第4引数に透明度を入力する。

[cpp]

ofEnableAlphaBlending();

ofSetColor(0,0,255,127);

[/cpp]

for 繰り返しを利用する

forを利用すれば、一度に複数の図形を書くことができます。

[cpp]

int i; for(i = 1 ; i < 5 ; i++){ ofCircle(200i ,120i , 80);

}

[/cpp]

update()を利用する

update()を利用すれば、オブジェクトを動かしたりすることができます。

[cpp]

define NUM 100

float loc_x[NUM]; float loc_y[NUM]; float radius;

float speedx[NUM]; float speedy[NUM];

//-------------------------------------------------------------- void testApp::setup(){

ofBackground(0 ,0 , 0);
ofEnableAlphaBlending();
ofEnableSmoothing();
ofSetCircleResolution(64);

radius = 20;
int i;
for (i=0; i< NUM; i++) {

    loc_x[i] = ofRandom(0, ofGetWidth());
    loc_y[i] = ofRandom(0, ofGetHeight());

    speedx[i] = ofRandom(0, 0.4);
    speedy[i] = ofRandom(0, 0.4);


}

}

//-------------------------------------------------------------- void testApp::update(){

int i;
for (i = 0;i < NUM; i++) {

loc_x[i] = loc_x[i] + speedx[i];
loc_y[i] = loc_y[i] + speedy[i];

if (loc_x[i] + radius > ofGetWidth()) {
    speedx[i] = speedx[i] *-1;
}

if (loc_y[i] + radius > ofGetHeight()) {

    speedy[i] *= -1;
}

if(loc_x[i] -radius < 0){
    speedx[i] *= -1;
}

if(loc_y[i] -radius < 0){
    speedy[i] *= -1;

}

void testApp::draw(){

int i;
ofSetColor(200,200, 29,79);


for (i=0; i < NUM ; i++) {


    ofCircle(loc_x[i], loc_y[i], radius);

}

}

[/cpp]

インタラクティブな動きを作る

マウスやキーボードで操作することで、動作を変化させることができます。 幸いopenFrameworksにはデフォルトのテンプレートで便利な関数が既に定義されています。

マウスの場合

[cpp]

void testApp::mouseMoved(int x, int y ){

}

void testApp::mouseDragged(int x, int y, int button){

}

void testApp::mousePressed(int x, int y, int button){

}

void testApp::mouseReleased(int x, int y, int button){

}

[/cpp]

引数のx ,y はマウスを動作した際のX座標の数字、Y座標の数字が代入されています。 bottomはよくわからにですが、int で数字は0になってました。

キーボード [cpp] void testApp::keyPressed(int key){

if (key == 'x'){ ; // 条件で実行したいコード } else if (key == 'y'){ ; // 他の条件で実行したいコード }

}

void testApp::keyReleased(int key){

} [/cpp]