Using AWT's Polygon class
From Processing
| Versions: | 1.0+ |
| Contributors: | eskimoblood |
| Started: | 2006-07-25 |
It is quite hard to check if a point is inside an irregular shape with the common Processing stuff. But it is easy with the java.awt.Shape/Polygon/Rectangle classes. Just call Shape.contains(x, y). See the code snippet to add this little feature in Processing.
Note: This method will not work if you transform or rotate shapes using the Processing rotate() or transform() functions, as the underlying java.awt.Polygon (or Rectangle, etc) will remain unmoved even though you will be drawing the shape at its translated position.
Source Code
/** * taken from http://wiki.processing.org/index.php/Using_AWT%27s_Polygon_class * @author Andreas Köberle */ Poly p; void setup() { int[] x = { 20, 40, 40, 60, 60, 20 }; int[] y = { 20, 20, 40, 40, 60, 60 }; p = new Poly(x, y, 6); } void draw(){ background(255); if (p.contains(mouseX, mouseY)) { fill(255, 0, 0); } else { fill(255); } p.drawMe(); } /* The class inherit all the fields, constructors and functions of the java.awt.Polygon class, including contains(), xpoint,ypoint,npoint */ class Poly extends java.awt.Polygon { public Poly(int[] x,int[] y, int n) { //call the java.awt.Polygon constructor super(x, y, n); } void drawMe() { beginShape(); for (int i = 0; i < npoints; i++) { vertex(xpoints[i], ypoints[i]); } endShape(CLOSE); } }