I have written generic Point classes, line/line intersection algorithms and Layer administration code more times than I can remember. I don't like menial programming, so this is effectively my code library. But you can use it too!
The language used is Processing, which is a mostly-Java-syntax language. I hardly ever use Java-specific ninja code, so rewriting any of these snippets to your favourite language is less than a minute's worth of work, typically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | /** * Let's find out which quadrant a point lies in with respect * to its unit circle axis system. This is very useful for * things like determining whether a point is "above" a line. */ void setup() { size(400,400); ellipseMode(CENTER); noCursor(); } void draw() { background(255); // line, at an angle float ox=20,oy=280,tx=380,ty=180; stroke(0,0,255); line(ox,oy,tx,ty); // mouse line float mx=(ox+tx)/2,my=(oy+ty)/2; stroke(255,0,0); line(mx,my, mouseX, mouseY); // step 1: get the normalised mouse vector float dx = mouseX-mx, dy = mouseY-my, len = sqrt(dx*dx+dy*dy); dx /= len; dy /= len; // step 2: get the normalised line vector float dxl = tx-ox, dyl = ty-oy, llen = sqrt(dxl*dxl+dyl*dyl); dxl /= llen; dyl /= llen; // step 3: get the normal (perpendicular) to the line vector float p = PI/2; float pdx = dxl * cos(p) - dyl * sin(p); float pdy = dxl * sin(p) + dyl * cos(p); // show what each of these normalised vectors look like float cx = 35, cy = 40; stroke(255,0,0); line(cx,cy,cx+10*dx,cy+10*dy); stroke(0,0,255); line(cx,cy,cx+10*dxl,cy+10*dyl); stroke(255,0,255); line(cx,cy,cx+10*pdx,cy+10*pdy); stroke(0); noFill(); ellipse(cx,cy,20,20); fill(0); text("UNIT CIRCLE", cx-30, cy-25); text("red: normalised mouse", cx+15, cy-9); text("blue: normalised line", cx+15, cy+5); text("magenta: perpendicular",cx+15, cy+18); // dot product magic: First, the dot product with // the original line tells us whether we're to the // "left" or "right" of our reference line's anchor, // irrespective of whether we're above or below the line. float dotproduct = dx*dxl + dy*dyl; text("blue: "+(dotproduct<0? "-":"+"), mouseX+10, mouseY-5); // more dot product magic: First, the dot product with // the line's normal (perpendicular line) tells us whether // we're "above" or "below" the line, irrespective of // whether we're left or right of the anchor. dotproduct = dx*pdx + dy*pdy; text("magenta: "+(dotproduct<0? "-":"+"), mouseX+10, mouseY+5); } |
Written and maintained by Mike "Pomax" Kamermans. All code snippets on this site are "do whatever you want with it" licensed.