配列とマウスインタラクション
提供:kuhalaboWiki
- 配列を使用して、複数のボールを動かす。
- mousePressedを使用して、ボールをマウスの位置に近づける。
#include "ofApp.h" static const int NUM = 10; //定数 ボールの個数 float x[NUM]; //円のx座標 float y[NUM]; //円のy座標 float radius[NUM]; //円の半径 int red[NUM]; int green[NUM]; int blue[NUM]; float loc_x[NUM]; float loc_y[NUM]; float speed_x[NUM]; float speed_y[NUM]; float acc_x[NUM]; float acc_y[NUM]; bool mouse_pressed; //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(0, 0, 0); //背景色の設定 ofSetColor(255, 255, 0); //描画色の設定 ofSetCircleResolution(64);//円の解像度 ofEnableAlphaBlending(); //アルファチャンネルを有効にする ofSetBackgroundAuto(false); //背景色での塗りつぶしなし ofSetFrameRate(30); //フレームレイト設定 mouse_pressed = false; //マウスの状態 for(int i = 0; i < NUM; i++){ loc_x[i] = ofRandom(0, ofGetWidth() ); loc_y[i] = ofRandom(0, ofGetHeight() ); speed_x[i] = ofRandom(-5, 5); speed_y[i] = ofRandom(-5, 5); radius[i] = ofRandom( 5, 20); red[i] = ofRandom(10, 255); green[i] = ofRandom(0, 200); blue[i] = ofRandom(10, 200); } } //-------------------------------------------------------------- void ofApp::update(){ for(int i = 0; i < NUM; i++){ acc_x[i] = ofRandom(-0.5,0.5); acc_y[i] = ofRandom(-0.5,0.5); if(mouse_pressed){ speed_x[i] = ( mouseX - loc_x[i] ) * 0.01; speed_y[i] = ( mouseY - loc_y[i] ) * 0.01; } else{ speed_x[i] = speed_x[i] + acc_x[i]; speed_y[i] = speed_y[i] + acc_y[i]; } if( loc_x[i] < 0 || loc_x[i] > ofGetWidth() ){ speed_x[i] = speed_x[i] * -1; } if( loc_y[i] < 0 || loc_y[i] > ofGetHeight() ){ speed_y[i] = speed_y[i] * -1; } loc_x[i] = loc_x[i] + speed_x[i]; loc_y[i] = loc_y[i] + speed_y[i]; } } //-------------------------------------------------------------- void ofApp::draw(){ //全画面を半透明の黒でフェード ofSetColor(0, 0, 0, 10); ofRect(0, 0, ofGetWidth(), ofGetHeight()); for(int i = 0; i < NUM; i++){ ofSetColor(red[i], green[i], blue[i]); ofCircle(loc_x[i],loc_y[i], radius[i]); } } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ mouse_pressed = true; } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ mouse_pressed = false; }