Created
August 31, 2014 10:32
-
-
Save antonmills/5396fe702c5b26f51da9 to your computer and use it in GitHub Desktop.
Detect if poly is convex or concave
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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