I'm looking to do a hit test on complex polygon shapes (basically, testing whether a mouse is over a state or country area on a map). I've tried the PGraphics buffer solution (color-picking), but ran into a wall when I found out that off-screen PGraphics buffers aren't supported in Processing.js (which is a requirement for the projects I'm working on).
So, I'd like to implement some sort of algorithm for hit test. I've found a lot of generic algorithms for this online, but the problem is that I have no idea how to adapt these for a Processing environment. Can anyone help me rewrite one of the algorithms below?
Here's one possibility, from
http://stackoverflow.com/questions/217578/point-in-polygon-aka-hit-test/2922778#2922778:
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy) { int i, j, c = 0; for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; } return c; }
public function Within( localP:Vector2 ):Boolean { for ( var i:int = 0; i<m_numPoints; i++ ) { var A:Vector2 = m_localSpacePoints[(i+1)%m_numPoints].Sub( m_localSpacePoints[i] ); var B:Vector2 = localP.Sub( m_localSpacePoints[i] ); if ( A.Wedge( B )<0 ) { // separating axis return false; } } return true; }
Thanks!
1