/** * collision_detection2.pde * * This program demonstrates collision detection in one dimension. * Two objects move toward each other and stop when they collide. * Collision is detected by comparing the distance between the objects' centers. * This only works for circular objects! * * created: 4-oct-2011/sklar * */ int d = 20; // diameter of objects PVector v1, v2; // velocities of objects PVector p1, p2; // positions of objects boolean running; // flag indicating that simulation is running /** * setup() */ void setup() { size( 800,600 ); v1 = new PVector( 1, 0, 0 ); p1 = new PVector( 0, (d+height)/2, 0 ); v2 = new PVector( -1, 0, 0 ); p2 = new PVector( width-d, (d+height)/2, 0 ); ellipseMode( CORNER ); running = true; } // end of setup() /** * draw() */ void draw() { if ( running ) { // clear screen background( #ffffff ); // draw two objects stroke( #333333 ); fill( #000066 ); ellipse( (int)p1.x, (int)p1.y, d, d ); fill( #006600 ); ellipse( (int)p2.x, (int)p2.y, d, d ); // update positions of objects p1.x += v1.x; p1.y += v1.y; p2.x += v2.x; p2.y += v2.y; // did we collide? if ( isCollision() ) { running = false; restart(); } } } // end of draw() /** * keyPressed() */ void keyPressed() { if (( key == 'q' ) || ( key == 'Q' )) { exit(); } else if (( key == 'r' ) || ( key == 'R' )) { restart(); } else if (( key == 's' ) || ( key == 'S' )) { running = ! ( running ); } } // end of keyPressed() /** * restart() */ void restart() { v1 = new PVector( 1, 0, 0 ); p1 = new PVector( 0, (d+height)/2, 0 ); v2 = new PVector( 1, 0, 0 ); p2 = new PVector( width-d, (d+height)/2, 0 ); } // end of restart() /** * isCollision() * this function returns true if the two objects have collided; false otherwise */ boolean isCollision() { float r = d/2; // radius of objects PVector p1center = new PVector( p1.x + r, p1.y + r ); // center of first object PVector p2center = new PVector( p2.x + r, p2.y + r ); // center of second object float d = sqrt( sq(p1center.x - p2center.x) + sq(p1center.y - p2center.y )); // distance between the centers of the two objects if ( d < 2 * r ) { return( true ); } else { return( false ); } } // end of isCollision()