Bevegelse
Krasj
Det er to involverte processing-filer:
_balls.js
/* we set up a number of moving balls and make them change direction when they collide */ // some balls var runners; var kuleRadius=15; function setup(){ var canvas = createCanvas(400, 400); canvas.parent('canvasHere'); runners=new Array(); var i=0; while(i<8){ runners[i]=new Ball(); // dont want to start with overlapping balls for(var j=0;j<i;j++) if(runners[j].touchBall(runners[i])) i-- i++ } } function draw(){ background(255); for(var i=0;i<runners.length;i++){ runners[i].drawMe(); } traffic(); } function traffic(){ // check collisions for(var i=0;i<runners.length;i++){ for(var j=i+1;j < runners.length; j++){ if(runners[i].touchBall(runners[j])){ runners[i].crash(runners[j]); } } } // move for(var i=0;i<runners.length;i++) runners[i].moveMe(); }
og
_oneBall.js
/* class describing a ball with position and speed */ function Ball(){ this.pos=createVector( random(kuleRadius,width-kuleRadius), random(kuleRadius,height-kuleRadius)); this.speed=createVector( random(-3.0,3.0), random(-3.0,3.0)); // draw it this.drawMe=function(){ fill(255,0,0); ellipse(this.pos.x,this.pos.y,kuleRadius*2,kuleRadius*2); // show speed line(this.pos.x,this.pos.y, this.pos.x+20*this.speed.x,this.pos.y+20*this.speed.y); } // move according to speed this.moveMe=function(){ this.pos.x+=this.speed.x; this.pos.y+=this.speed.y; //make sure we are on sketch if(this.pos.x+kuleRadius > width) this.speed.x=-abs(this.speed.x); if(this.pos.x-kuleRadius <0) this.speed.x=abs(this.speed.x); if(this.pos.y +kuleRadius >height) this.speed.y=-abs(this.speed.y); if(this.pos.y -kuleRadius<0) this.speed.y=abs(this.speed.y); } // do this ball overlap an other ball this.touchBall=function(otherBall){ return this.pos.dist(otherBall.getPos()) <= 2*kuleRadius; } // crash this.crash=function(otherBall){ // swap speed var oldSpeed=this.speed; this.speed=otherBall.getSpeed(); otherBall.setSpeed(oldSpeed); playClick(); } this.getSpeed=function(){ return this.speed; } this.setSpeed=function(s){ this.speed=s; } this.getPos=function(){ return this.pos; } }
Javascriptkoden som kaller lyden er slik:
_index.js
function playClick(){ var theSound=document.getElementById('hit'); theSound.pause(); theSound.play(); }
Du kan inspisere denne strukturen på denne siden:
test.html
https://borres.hiof.no/wep/proc/p5js/balls/test.html