Bevegelse
Krasj
Det er t0 involverte processing-filer:
_crashingBalls.pde
/* we set up a number of moving balls and make them change direction when they collide */ //import ddf.minim.*; //Minim minim; //AudioSample hit; // some balls Ball[] runners; void setup(){ size(600,600); //minim = new Minim(this); // load hit.wav from the data folder /*hit = minim.loadSample( "hit.mp3", // filename 512 // buffer size );*/ // make balls runners=new Ball[10]; for(int i=0;i<runners.length;i++){ runners[i]=new Ball(color(255,0,0),i); // we dont want to start with overlapping balls for(int j=0;j<i;j++) if(runners[j].touchBall(runners[i])) runners[i].visible=false; } } void draw(){ background(255); // draw for(int i=0;i<runners.length;i++){ runners[i].drawMe(); } // collisions and move traffic(); } void traffic(){ // check collisions for(int i=0;i<runners.length;i++){ for(int j=i+1;j < runners.length; j++){ if(runners[i].touchBall(runners[j])){ runners[i].crash(runners[j]); } } } // move (with new speeds) for(int i=0;i<runners.length;i++) runners[i].moveMe(); }
og
_Ball.pde
/* class describing a ball with position, speed, color, radius speed is interpreted as points pr frame extended from simple_balls */ class Ball{ PVector pos; PVector speed; color c; float radius; boolean visible; int index; Ball(color c,int index){ this.c=c; this.index=index; pos=new PVector(random(radius,width-radius),random(radius,height-radius)); speed=new PVector(random(-3.0,3.0),random(-3.0,3.0)); radius=15; visible=true; } // draw it if it is visble void drawMe(){ if(visible){ fill(c); ellipse(pos.x,pos.y,radius*2,radius*2); // show index fill(0); text(index,pos.x,pos.y); // show speed PVector copyOfPos=pos.get(); PVector copyOfSpeed=speed.get(); copyOfSpeed.mult(20);// a reasonable number copyOfPos.add(copyOfSpeed); line(pos.x,pos.y,copyOfPos.x,copyOfPos.y); } } // move according to speed void moveMe(){ pos.add(speed); //make sure we are on sketch and avoid flickering if(pos.x+radius > width) speed.x=-abs(speed.x); if(pos.x-radius <0) speed.x=abs(speed.x); if(pos.y +radius >height) speed.y=-abs(speed.y); if(pos.y -radius<0){ speed.y=abs(speed.y); } } // do this ball overlap an other ball boolean touchBall(Ball otherBall){ if(!visible) return false; if(!otherBall.visible) return false; return pos.dist(otherBall.pos) <= radius+otherBall.radius; } // what we do when they overlap, crash void crash(Ball otherBall){ // will not crash if one of them is not visible if(otherBall.visible && visible){ // swap speed PVector oldSpeed=speed.get(); speed=otherBall.speed.get(); otherBall.speed=oldSpeed.get(); playClick(); } } }
Javascriptkoden er slik, med to funksjoner som kaller skissen:
_index.js
function playClick(){ var theSound=document.getElementById('hit'); theSound.pause(); theSound.play(); }