Difference between revisions of "IsPointInPolygon2D"

From Second Life Wiki
Jump to navigation Jump to search
Line 8: Line 8:
|p2_type=list|p2_name=polygon|p2_desc=A polygon described as a list of 2D vectors for its points
|p2_type=list|p2_name=polygon|p2_desc=A polygon described as a list of 2D vectors for its points
|mode=user
|mode=user
|cat1=LSL Examples
|cat1=Examples
|cat2=Library
|examples=if (isPointInPolygon2D(<0.5,0.5,0>, [<0,0,0>, <0,1,0>, <1,1,0>, <1,0,0>])) llOwnerSay("Point is in polygon");
|examples=if (isPointInPolygon2D(<0.5,0.5,0>, [<0,0,0>, <0,1,0>, <1,1,0>, <1,0,0>])) llOwnerSay("Point is in polygon");
}}
}}
Line 58: Line 59:
     return inPoly != 0;
     return inPoly != 0;
}</lsl>
}</lsl>
[[Category:LSL Library]]
[[Category:LSL Examples]]

Revision as of 05:21, 10 August 2008

Summary

Function: integer isPointInPolygon2D( vector point, list polygon );

Tests a polygon (described as a list of 2D vectors) to see if a 2D point lies within it. Useful for detecting where an event occurred within 2D space.
Returns an integer TRUE if the point lies within the described polygon, FALSE if not

• vector point The point to test for, described by a 2D vector (a vector using only the x and y values)
• list polygon A polygon described as a list of 2D vectors for its points

It is possible (and fairly easy) to adapt this function to use a list of paired floats, both implementations are provided.

Examples

if (isPointInPolygon2D(<0.5,0.5,0>, [<0,0,0>, <0,1,0>, <1,1,0>, <1,0,0>])) llOwnerSay("Point is in polygon");

Implementations

Vectors

<lsl>integer isPointInPolygon2D(vector point, list polygon) {

   integer l = polygon != []; 
   integer i = 0; integer j = l - 1; integer inPoly = FALSE; 
   vector iv; vector jv; float diffY;
   while (i < l) { 
       iv = llList2Vector(polygon, i); 
       jv = llList2Vector(polygon, j); 
    
       diffY = (jv.y - iv.y); 
       if (diffY == 0.0) diffY = 1000.0; 
    
       if ((((iv.y <= point.y) && 
           (point.y < (jv.x - iv.x) * (point.y - iv.y) / diffY + iv.x)))) 
           inPoly = !inPoly; 
        
       j = i++;
   }
   return inPoly != 0;

}</lsl>

Float-pairs

<lsl>integer isPointInPolygon2D(float x, float y, list polygon) {

   integer l = polygon != [];
   integer i = 0; integer j = l - 2; integer inPoly = FALSE;
   float ix; float iy; float jx; float jy; float diffY;
   while (i < l) {
       ix = llList2Float(polygon, i);
       iy = llList2Float(polygon, ++i);
       jx = llList2Float(polygon, j);
       jy = llList2Float(polygon, ++j);
    
       diffY = (jy - iy); 
       if (diffY == 0.0) diffY = 1000.0; 
    
       if ((((iy <= y) && 
           (y < (jx - ix) * (y - iy) / diffY + ix)))) 
           inPoly = !inPoly; 
        
       j = i++;
   }
   return inPoly != 0;

}</lsl>