ランダムウォーク
提供:kuhalaboWiki
				
								
				(版間での差分)
				
																
				
				
								
				 (ページの作成:「;ランダムに東西南北の方角に歩くアリ  ;Ball.h <pre> #pragma once #include "ofMain.h"  class Ball { public: 	ofPoint pos; 	float radius; 	ofColor bcolor;...」)  | 
			
2014年11月17日 (月) 03:08時点における版
- ランダムに東西南北の方角に歩くアリ
 
- Ball.h
 
#pragma once
#include "ofMain.h"
class Ball {
public:
	ofPoint pos;
	float radius;
	ofColor bcolor;
	int dw;  // 歩幅
	Ball();
	void draw();
	void update();
};
- Ball.cpp
 
#include "Ball.h"
Ball::Ball(){
	pos = ofPoint(ofGetWidth()/2, ofGetHeight()/2);
	radius = ofRandom(10,20);
	bcolor = ofColor(ofRandom(0,255), ofRandom(0,255), ofRandom(0,255), 100);
	dw= 20;
}
void Ball::update(){
	int d = ofRandom(0, 4); //0から3までの乱数を発生
	switch(d)
	{
	   case 0:  // 東(X軸の正)へ進む
		pos.x += dw;
                break;
           case 1:  // 西(X軸の負)へ進む
		pos.x -= dw;
                break;
	   case 2:  // 南(Y軸の正)へ進む
		pos.y += dw;
                break;
	   case 3:  // 北(Y軸の負)へ進む
		pos.y -= dw;
                break;
        }
	if( pos.x > ofGetWidth() )  pos.x = 0;
	if( pos.x < 0 )  pos.x = ofGetWidth();
	if( pos.y > ofGetHeight() ) pos.y = 0;
	if( pos.y < 0 ) pos.y = ofGetHeight();
}
void Ball::draw(){
	ofSetColor(bcolor);
	ofCircle(pos.x, pos.y, radius);
}
- ofApp.h
 
#pragma once
#include "ofMain.h"
#include "Ball.h"
class ofApp : public ofBaseApp{
public:
	static const int NUM = 2; //配列の大きさを指定
	void setup();
	void update();
	void draw();
	void keyPressed(int key);
	void keyReleased(int key);
	void mouseMoved(int x, int y );
	void mouseDragged(int x, int y, int button);
	void mousePressed(int x, int y, int button);
	void mouseReleased(int x, int y, int button);
	void windowResized(int w, int h);
	void dragEvent(ofDragInfo dragInfo);
	void gotMessage(ofMessage msg);
		
	Ball balls[NUM]; //Ballクラスのインスタンスを配列で指定
};
- ofApp.cpp
 
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
	ofBackground(0, 0, 0); //背景色の設定
	ofSetColor(255, 255, 0); //描画色の設定
	ofSetBackgroundAuto(false);
	ofSetFrameRate(20);
	ofEnableAlphaBlending();  //アルファチャンネルを有効にする
	ofSetCircleResolution(64);
}
//--------------------------------------------------------------
void ofApp::update(){
	for(int i = 0; i < NUM; i++){
		balls[i].update();
	}
}
//--------------------------------------------------------------
void ofApp::draw(){
	for(int i = 0; i < NUM; i++){
		balls[i].draw();
	}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}