Advertisement
gmlscripts

polygon_is_convex

Feb 4th, 2016
432
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /// polygon_is_convex(polygon)
  2. //
  3. //  Returns true if a given 2D polygon is convex, false otherwise.
  4. //
  5. //      polygon     ds_list of an ordered series of coordinate
  6. //                  pairs defining the shape of a polygon
  7. //
  8. //  Polygon vertices can be given in clockwise or counter-clockwise order.
  9. //  Polygons are closed figures with edges spanning consecutive vertices
  10. //  and from the last vertex to the first. Polygons must be simple, which
  11. //  means they cannot have edges that cross one another.
  12. //
  13. //  eg. square polygon = { 100,100,  100,200,  200,200,  200,100 }
  14. //
  15. /// GMLscripts.com/license
  16. {
  17.     var zp = false;
  18.     var zn = false;
  19.  
  20.     var polygon = argument0;
  21.     var size = ds_list_size(polygon);
  22.  
  23.     for (var i=0; i<size; i+=2) {
  24.         var j = (i+2) mod size;
  25.         var k = (i+4) mod size;
  26.        
  27.         var x0 = ds_list_find_value(polygon, i);
  28.         var y0 = ds_list_find_value(polygon, i+1);
  29.         var x1 = ds_list_find_value(polygon, j);
  30.         var y1 = ds_list_find_value(polygon, j+1);
  31.         var x2 = ds_list_find_value(polygon, k);
  32.         var y2 = ds_list_find_value(polygon, k+1);
  33.        
  34.         var z = (x1-x0) * (y2-y1) - (y1-y0) * (x2-x1);
  35.  
  36.         if (z > 0) zp = true;
  37.         else if (z < 0) zn = true;
  38.  
  39.         if (zp && zn) return false;
  40.     }
  41.     return true;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement