|
| 1 | +/* |
| 2 | +POINT/POLYGON COLLISION DETECTION |
| 3 | + Jeff Thompson | 2013 | www.jeffreythompson.org |
| 4 | + |
| 5 | + Finds collisions betwen a point and a N-sided polygon - very |
| 6 | + flexible! |
| 7 | + |
| 8 | + Via: http://stackoverflow.com/a/2922778/1167783 |
| 9 | + */ |
| 10 | + |
| 11 | +int numVertices = 4; // number of sides in polygon |
| 12 | +float[] vertX = new float[numVertices]; // array of x/y coordinates for polygon |
| 13 | +float[] vertY = new float[numVertices]; |
| 14 | + |
| 15 | +void setup() { |
| 16 | + size(500, 500); |
| 17 | + smooth(); |
| 18 | + noStroke(); |
| 19 | + |
| 20 | + // create vertices for polygon (here a trapezoid) |
| 21 | + vertX[0] = 100; |
| 22 | + vertY[0] = 100; |
| 23 | + vertX[1] = width-100; |
| 24 | + vertY[1] = 100; |
| 25 | + vertX[2] = width-200; |
| 26 | + vertY[2] = height-100; |
| 27 | + vertX[3] = 200; |
| 28 | + vertY[3] = height-100; |
| 29 | +} |
| 30 | + |
| 31 | +void draw() { |
| 32 | + background(150, 50, 0); |
| 33 | + |
| 34 | + // if hit, change the fill color for the polygon |
| 35 | + if (pointPolygon(numVertices, vertX, vertY, mouseX, mouseY)) { |
| 36 | + fill(255); |
| 37 | + } |
| 38 | + else { |
| 39 | + fill(255, 0, 0); |
| 40 | + } |
| 41 | + |
| 42 | + // draw polygon |
| 43 | + beginShape(); |
| 44 | + for (int i=0; i<numVertices; i++) { |
| 45 | + vertex(vertX[i], vertY[i]); |
| 46 | + } |
| 47 | + endShape(CLOSE); |
| 48 | + |
| 49 | + // draw cursor |
| 50 | + fill(0); |
| 51 | + ellipse(mouseX, mouseY, 30, 30); |
| 52 | +} |
| 53 | + |
| 54 | +/* |
| 55 | +POINT/POLYGON COLLISION DETECTION |
| 56 | + Takes 5 arguments: |
| 57 | + + # of vertices |
| 58 | + + float array x and y coordinates for vertices |
| 59 | + + x/y coordinates for point |
| 60 | + */ |
| 61 | +boolean pointPolygon (int numVertices, float[] vertX, float[] vertY, float px, float py) { |
| 62 | + boolean collision = false; |
| 63 | + for (int i=0, j=numVertices-1; i < numVertices; j = i++) { |
| 64 | + if ( ((vertY[i]>py) != (vertY[j]>py)) && (px < (vertX[j]-vertX[i]) * (py-vertY[i]) / (vertY[j]-vertY[i]) + vertX[i]) ) { |
| 65 | + collision = !collision; |
| 66 | + } |
| 67 | + } |
| 68 | + return collision; |
| 69 | +} |
| 70 | + |
0 commit comments