Path: blob/main/public/games/files/garbage-collector/js/geometry/polygon.js
1036 views
/*globals define*/1define([2'object2d',3'utils'4], function( Object2D, Utils ) {5'use strict';67function Polygon( x, y ) {8Object2D.call( this, x, y );910this.vertices = [];11}1213Polygon.prototype = new Object2D();14Polygon.prototype.constructor = Polygon;1516Polygon.prototype.draw = function( ctx ) {17if ( !this.vertices.length ) {18return;19}2021Object2D.prototype.draw.call( this, ctx );22};2324Polygon.prototype.drawPath = function( ctx ) {25var vertexCount = this.vertexCount();2627ctx.beginPath();2829ctx.moveTo( this.vertices[0], this.vertices[1] );30for ( var i = 1; i < vertexCount; i++ ) {31ctx.lineTo( this.vertices[ 2 * i ], this.vertices[ 2 * i + 1 ] );32}3334ctx.closePath();35};3637Polygon.prototype.drawNormals = function( ctx, options ) {38options = options || {};3940var length = options.length || 10,41lineWidth = options.lineWidth || 2,42stroke = options.stroke || '#0f0';4344var vertexCount = this.vertexCount();4546ctx.beginPath();4748var xi, yi, xj, yj;49var mx, my;50var normal;51for ( var i = 0; i < vertexCount; i++ ) {52xi = this.vertices[ 2 * i ];53yi = this.vertices[ 2 * i + 1 ];54xj = this.vertices[ 2 * ( ( i + 1 ) % vertexCount ) ];55yj = this.vertices[ 2 * ( ( i + 1 ) % vertexCount ) + 1 ];5657mx = 0.5 * ( xi + xj );58my = 0.5 * ( yi + yj );5960normal = Utils.lineNormal( xi, yi, xj, yj );61if ( !normal ) {62continue;63}6465ctx.moveTo( mx, my );66ctx.lineTo( mx + normal.x * length, my + normal.y * length );67}6869ctx.lineWidth = lineWidth;70ctx.strokeStyle = stroke;71ctx.stroke();72};7374Polygon.prototype.vertexCount = function() {75return 0.5 * this.vertices.length;76};7778Polygon.prototype.contains = function( x, y ) {79var vertexCount = this.vertexCount();8081var point = this.toLocal( x, y );82x = point.x;83y = point.y;8485var contains = false;86var xi, yi, xj, yj;87for ( var i = 0, j = vertexCount - 1; i < vertexCount; j = i++ ) {88xi = this.vertices[ 2 * i ];89yi = this.vertices[ 2 * i + 1 ];90xj = this.vertices[ 2 * j ];91yj = this.vertices[ 2 * j + 1 ];9293if ( ( ( yi > y ) !== ( yj > y ) ) &&94( x < ( xj - xi ) * ( y - yi ) / ( yj - yi ) + xi ) ) {95contains = !contains;96}97}9899return contains;100};101102return Polygon;103});104105106