laliki
YaBB Newbies
Offline
Posts: 3
Re: intersection of two circles
Reply #1 - Oct 8th , 2008, 11:58pm
// Select four points: center 1, radius 1, center 2, radius 2. // The circles and their intersections are drawn, // the coordinates of all points are printed to the console. // Needs explanation???? int pointCounter; int c1x,c1y; int c2x,c2y; float r1,r2; void setup(){ size(600,600); background(210,210,170); initVars(); } void draw(){ if(c1x<0){ background(210,210,170); } else { if(c1x>=0){ noStroke(); fill(255,80,0); ellipse(c1x,c1y,5,5); } if(r1>0){ stroke(0); noFill(); ellipse(c1x,c1y,2*r1,2*r1); } if(c2x>=0){ noStroke(); fill(255,100,0); ellipse(c2x,c2y,5,5); } if(r2>0){ stroke(0); noFill(); ellipse(c2x,c2y,2*r2,2*r2); println("****"); println("Center 1 : ("+c1x+", "+c1y+"), radius 1 : "+r1+ "; Center 2 : ("+c2x+", "+c2y+ ") radius 2 :"+r2); intersections(); } } } // compute and draw intersections void intersections(){ float d=dist(c1x,c1y,c2x,c2y); // distance between centers float base,h; // auxiliary distances // p, middle point between q1 and q2 // q1 dn q2 intersection points float px,py,q1x,q1y,q2x,q2y; stroke(255,0,0); noFill(); line(c1x,c1y,c2x,c2y); if(d<abs(r1-r2) || d>r1+r2) println("C1 and C2 do not intersect"); else if(d==abs(r1-r2)){ // one inside the other, intersect in one point if(r1>r2) base=r1; else base=-r1; px=c1x+base*(c2x-c1x)/d; py=c1y+base*(c2y-c1y)/d; noStroke(); fill(255,0,100); ellipse(px,py,5,5); println("intersection: P=("+ px+ ", "+ py+ ")"); } else if(d==r1+r2){ // outside each other, intersect in one point base=r1; px=c1x+base*(c2x-c1x)/d; py=c1y+base*(c2y-c1y)/d; noStroke(); fill(255,0,100); ellipse(px,py,5,5); println("intersection: P=("+ px+ ", "+ py+ ")"); } else{ // intersect in two points base=(r1*r1-r2*r2+d*d)/(2*d); h=sqrt(r1*r1-base*base); px=c1x+base*(c2x-c1x)/d; py=c1y+base*(c2y-c1y)/d; q1x=px+h*(c2y-c1y)/d; q1y=py-h*(c2x-c1x)/d; q2x=px-h*(c2y-c1y)/d; q2y=py+h*(c2x-c1x)/d; noStroke(); fill(255,0,100); ellipse(px,py,5,5); ellipse(q1x,q1y,5,5); ellipse(q2x,q2y,5,5); println("intersections: Q1=("+ q1x+ ", "+ q1y+ ") and Q2=("+q2x+ ", "+ q2y+")"); } noLoop(); } void initVars(){ c1x=-1; c1y=-1; r1=0; c2x=-1; c2y=-1; r2=0; pointCounter=0; } void mousePressed(){ // first point selected is the center of circle 1 // second point selected is on circle 1 // third point selected is the center of circle 2 // fourth point selected is on circle 2 loop(); switch(pointCounter){ case 0: c1x=mouseX; c1y=mouseY; pointCounter++; break; case 1: r1=dist(c1x,c1y,mouseX,mouseY); pointCounter++; break; case 2: c2x=mouseX; c2y=mouseY; pointCounter++; break; case 3: r2=dist(c2x,c2y,mouseX,mouseY); pointCounter++; } } void keyPressed(){ loop(); initVars(); }