mathmatical question.. - Reply
- Posted by "BABOR, JIRI" <J.Babor at GNS.CRI.NZ> May 29, 1997
- 777 views
Lee woo seob wrote: > Can anyone give me nice answer over the problem below; > Assumes the polygon with arbitrary numbers of points is drawn on the > pixel-graphics screen, for example; > polygon(RED,1,{{100,200},{200,200},......,} > Problem is: > How can I know whether the mouse pointer is INSIDE the polygon or not, > at the time the mouse button is pressed? I am not sure I can give you a nice answer, but I thought it was interesting enough problem. I am assuming you already know how to get the mouse pointer coordinates - if not, please ask again. There are several possible approaches to this problem, I simply coded the first one that occurred to me: imagine a straight line through the point. In a non-trivial case, the line will intersect with one or more sides of the polygon. Now, travel from the given point in one or the other direction and count the intersections. If the total is odd, you obviously started inside the polygon and vice versa. - Incidentally, I chose a horizontal line in the function inside() below, sequence p is x,y coordinates of the point, and P is the polygon sequence. Jiri Sorry, this is almost as long as some of Ralf's messages... -- inpoly.ex ------------------------------------------------------------------- -- j.babor at gns.cri.nz -------------------------------------------------------------------------------- include graphics.e include get.e object junk sequence s,p1,p2,p3 integer key function inside(sequence p, sequence P) atom x integer count,n n=length(P) P=append(P,P[1]) count=0 for i=1 to n do if (P[i][2]<p[2] and P[i+1][2]>p[2]) or (P[i][2]>p[2] and P[i+1][2]<p[2]) then x=P[i][1]+(p[2]-P[i][2])*(P[i+1][1]-P[i][1])/(P[i+1][2]-P[i][2]) if x<p[1] then count=count+1 end if end if end for return remainder(count,2) -- return 1 (true) if count is odd end function -- main ------------------------------------------------------------------------ junk=graphics_mode(18) p1={30,250} p2={80,250} p3={200,250} polygon(12,1,s) pixel(15,p1) pixel(14,p2) pixel(9,p3) print(1,{inside(p1,s),inside(p2,s),inside(p3,s)}) --printf(1,"%d",inside(p1,s)) key = wait_key() junk=graphics_mode(-1)