Skip to content

Instantly share code, notes, and snippets.

@antonmills
Created August 31, 2014 10:32
Show Gist options
  • Select an option

  • Save antonmills/5396fe702c5b26f51da9 to your computer and use it in GitHub Desktop.

Select an option

Save antonmills/5396fe702c5b26f51da9 to your computer and use it in GitHub Desktop.
Detect if poly is convex or concave
/**
* Tests if a Polygon shape is convex.
* Pass an Array of vertices(or points) that have x/y properties
*
* @return {Boolean} true is a convex shape
*/
Polygon.prototype.isConvex = function()
{
if (this.vertices.length < 4)
return true;
var sign = false;
var n = this.vertices.length;
for(var i= 0; i < n; i++)
{
var dx1 = this.vertices[(i + 2) % n].x - this.vertices[(i + 1) % n].x;
var dy1 = this.vertices[(i + 2) % n].y - this.vertices[(i + 1) % n].y;
var dx2 = this.vertices[i].x - this.vertices[(i + 1) % n].x;
var dy2 = this.vertices[i].y - this.vertices[(i + 1) % n].y;
var zcrossproduct = dx1 * dy2 - dy1 * dx2;
if(i == 0)
{
sign = zcrossproduct > 0;
} else
{
if (sign != (zcrossproduct > 0))
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment