| versions | 0095+ |
|---|
| contributors | eskimoblood |
| started on | 2006-07-25 14:25 |
Its quite hard to check if a point is inside an irregular shape with the common processing stuff. But it's easy with the java.awt.Shape/Polygon/Rectangle classes. Just call Shape.intersect(int x, int y). See the code how to add this little feature in proccesing.
/** using-awt-s-polygon-class-to-test-for-insideness taken from http://processinghacks.com/hacks:using-awt-s-polygon-class-to-test-for-insideness @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); fill(255); if(p.contains(mouseX,mouseY))fill(255,0,0); 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(); } }
Note that 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. Make this modification to the above example's draw() function for an illustration of this behavior:
void draw(){ background(255); fill(255); translate(20,20); if(p.contains(mouseX,mouseY))fill(255,0,0); p.drawMe(); }
The figure will not turn red when you mouse over it, as before. Instead, it will turn red only when you mouse over the untranslated position where the underlying java.awt.Polygon is still positioned.