shipshape
shipshape

Reputation: 1742

Point in Polygon Hit Test in JavaScript (Chrome bug)

I am working on a game written in javaScript / jQuery. Part of my code draws a random polygon (an island) on a tile grid. I need to check if a point is inside the polygon.

I am using a point-in-polygon intersection script which I found in several places on Stack Overflow (original here). This works fine in Firefox. In Chrome, there are points inside the polygon which the script says are not inside it.

In Firefox: enter image description here

In Chrome (the island is different because they are randomly generated): enter image description here

Please take a look at the source here, particularly the pointPolygonIntersect function: Point in Polygon Hit Test

Can anyone figure out why this is happening? The original script is in C, and I am using a JavaScript version - could this be causing the problem?

Upvotes: 4

Views: 2200

Answers (2)

Jonathan
Jonathan

Reputation: 1507

Pick an island and stick with it. Trace the code in both browsers and see where they differ. There's no reason to fight against the randomness that you can easily remove...

Upvotes: 2

japrescott
japrescott

Reputation: 5023

I gave it a quick look. Couldn't track the app flow, but what seems strange is the

c = !c;

line of code. Why dont you just set it to true, or directly return true, if you meet the conditions the first time? I'm assuming, that chrome goes to "true" and then inverts it the next time its within the x/y bounds.

I'm not familiar with Raphael or SVG, but it seems your polygons are squares, thus you could do a simple within test

//original found here http://www.gamedev.net/topic/483716-point-inside-of-rectangle/
function inside( x, y, l, r, b, t ){ //x,y are the point, l,r,b,t are the extents of the rectangle
    return x > l && x < r && y > b && y < t;
}

Upvotes: 0

Related Questions