/** * collision_detection1.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 bounding boxes of the two objects. * * The two objects are the same size as each other. * * created: 4-oct-2011/sklar * */ int d = 100; // 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. * we have to check if each corner of bounding box of each object is contained within the bounding box of the other. * note that because the objects are the same size, we only have to check if the first is within the second. * (we would have to check for containment in both relationships if the objects were different sizes.) */ boolean isCollision() { if ((( p2.x <= p1.x + d ) && ( p1.x + d <= p2.x + d ) && ( p2.y <= p1.y + d ) && ( p1.y + d <= p2.y + d )) || // is lower right corner of p1 inside p2 (same as upper left corner of p2 inside p1)? (( p2.x <= p1.x ) && ( p1.x <= p2.x + d ) && ( p2.y <= p1.y + d ) && ( p1.y + d <= p2.y + d )) || // is lower left corner of p1 inside p2 (same as upper right corner of p2 inside p1)? (( p2.x <= p1.x + d ) && ( p1.x + d <= p2.x + d ) && ( p2.y <= p1.y ) && ( p1.y <= p2.y + d )) || // is upper right corner of p1 inside p2 (same as lower left corner of p2 inside p1)? (( p2.x <= p1.x ) && ( p1.x <= p2.x + d ) && ( p2.y <= p1.y ) && ( p1.y <= p2.y + d ))) { // is upper left corner of p1 inside p2 (same as lower right corner of p2 inside p1)? return( true ); } else { return( false ); } } // end of isCollision()