fireflies

int flyNum = 45;
firefly[] fireflies = new firefly[flyNum];
PImage bg;

void setup(){
size(600,600);
frameRate(30);
noStroke();
smooth();

bg = loadImage(”bg.jpg”);
image(bg,0,0);

for( int i = 0; i < flyNum; i ++ ){
fireflies[i] = new firefly( random(width), random(400), int(random(360)), i, 1, int(random(1000)), fireflies);
}
}

void draw(){
image(bg,0,0);
for( int i = 0; i < flyNum; i ++ ){
if(fireflies[i].wallCollide()){
fireflies[i].turnLeft();
}
if( fireflies[i].fireflyCollide()){
fireflies[i].turnRight();
}
fireflies[i].move();
if( fireflies[i].shining() > 0 ){
fireflies[i].display();
}
}

}

class firefly {
float x;
float y;
int angle; //direction
int s; //speed;
int id;
int shine;
firefly[] others;

firefly( float tempX, float tempY, int tempAngle, int tempID, int tempS, int tempShine, firefly[] tempflies ){
x = tempX;
y = tempY;
id = tempID;
angle = tempAngle;
s = tempS;
shine = tempShine;
others = tempflies;
}

void turnLeft(){
if( angle < 350){
angle += 10;
}
else{
angle -= 350;
}
}

void turnRight(){
if( angle >= 10){
angle -= 10;
}
else{
angle += 350;
}
}

void move(){
x += s*sin(radians(angle));
y -= s*cos(radians(angle));
}

boolean wallCollide(){
if( x < 0 ){
x = width;
}
else if( x > width ) {
x = 0;
}
else if( y < 0 ){
//angle += 180;
return true;
}
else if( y > 400 ){
//angle -= 180;
return true;
}
return false;
}

boolean fireflyCollide(){
for( int i = 0; i < flyNum; i ++ ){
if( i != id ){
if( distance( x, y, others[i].x, others[i].y ) < 20 ){
return true;
}
}
}
return false;
}

int shining(){
if( shine == 1000){
shine = int( random(-600, 0));
}
shine ++;
return shine;
}

void display(){
for( int i = 12; i >= 0 ; i -= 3) {
fill(255,255,160,255-i*20);
ellipse( x, y, i, i );
}
}
}

float distance( float a, float b, float c, float d){
return ( sqrt(( a - c )*( a - c ) + ( b - d )*( b - d )));
}

click here to see the program


About this entry