Hi, i’m trying to get into programming again and a stubbled upon a little problem. I was trying to create a hexagon but I can’t figure out a smart way to detect when my mouse is inside of the shape. Any good ideas?
void setup() {
fullScreen();
}
void draw() {
background(102);
polygon(width0.5, height0.5, 15, 6); //6-kant
}
void polygon(float x, float y, float radius, int npoints) {
float angle = TWO_PI / npoints;
beginShape();
for (float a = 0; a < TWO_PI; a += angle) {
float sx = x + cos(a) * radius;
float sy = y + sin(a) * radius;
vertex(sx, sy);
}
endShape(CLOSE);
}
You’re in luck – I have a method for this (change the parameters/modify as you see fit):
/**
* Determine if a point is in a polygon, given by a list of its vertices.
*
* @param s PShape
* @param point PVector point to check
* @return boolean
*/
private static final boolean pointInPoly(PShape s, PVector point) {
boolean within = false;
int j = s.getVertexCount() - 1;
for (int i = 0; i < s.getVertexCount(); i++) {
final PVector v = s.getVertex(i);
final PVector b = s.getVertex(j);
if (((v.y > point.y) != (b.y > point.y)) && (point.x < (b.x - v.x) * (point.y - v.y) / (b.y - v.y) + v.x)) {
within = !within;
}
j = i;
}
return within;
}