sebogawa
YaBB Newbies
Offline
Posts: 13
Re: URGENT Help with collision detection and movem
Reply #9 - Dec 9th , 2008, 10:55pm
i found the following code for a billards game and now im working on deciphering it so i can extract the collision detection and add it to my bumper balls game...this is gonna be a long night (: /** * Welcome to Skanaar microBilliard<br><br> * * Click, drag and release on a ball to give it a push.<br> * numerical keys 1-4 respawns different number of balls **/ Table game; //-------------- void setup(){ size(210,330); smooth(); game = new Table(6,5,200,300); game.startGame(); } //-------------- void draw(){ background(32); game.update(); game.visualize(); } //-------------- void keyPressed(){ println( game.kineticEnergy() ); } //-------------- void mousePressed(){ game.mousePressed(mouseX-game.x,mouseY-game.y); } //-------------- void mouseReleased(){ game.mouseReleased(mouseX-game.x,mouseY-game.y); } //============================= class Table{ float drag = 0.985; float elasticity = 0.9; float wallElasticity = 0.8; float pushFactor = 0.05; float maxPush = 10; color[] ballColors = new color[]{color(192),color(192,64,32),color(64,192,0)}; Ball[] balls; Ball selectedBall; int x,y,width,height; //-------------- Table(int x, int y, int w, int h){ this.x = x; this.y = y; width = w; height = h; } //-------------- void startGame(){ buildBalls(8); } //-------------- void buildBalls(int count){ balls = new Ball[2*count+1]; for(int i=0;i<count;i++) balls[i] = new Ball( random(width), random(height),1, this); for(int i=0;i<count;i++) balls[count+i] = new Ball( random(width), random(height),2, this); balls[2*count] = new Ball( 0.5*(width), 0.5*(height),0, this); } //-------------- void update(){ //simulation for(int i=0;i<balls.length;i++) balls[i].update(); //collision detection for(int i=0;i<balls.length;i++) for(int j=i+1;j<balls.length;j++) balls[i].collisionDetect(balls[j]); } //-------------- void visualize(){ translate(x,y); noStroke(); fill(0,128,0); rect(0,0,width,height); //draw que stroke(255); if(mousePressed && selectedBall != null) line(selectedBall.x,selectedBall.y,mouseX-x,mouseY-y); //drawing for(int i=0;i<balls.length;i++) balls[i].visualize(); } //-------------- float kineticEnergy(){ float energy=0; for(int i=0;i<balls.length;i++) energy += mag( balls[i].vx, balls[i].vy ); return energy; } //-------------- void mousePressed(int mx, int my){ for(int i=0;i<balls.length;i++) if( dist(balls[i].x,balls[i].y,mx,my) < balls[i].radius) { selectedBall = balls[i]; break; } } //-------------- void mouseReleased(int mx, int my){ if(selectedBall != null){ float px = (selectedBall.x-mx) * pushFactor; float py = (selectedBall.y-my) * pushFactor; float push = mag(px,py); if( push > maxPush ){ px = maxPush*px/push; py = maxPush*py/push; } selectedBall.push(px,py); } selectedBall = null; } }