Get simpler polygons by removing collinear points

In geometry, collinearity is a property of a set of points, specifically, the property of lying on a single line. A set of points with this property is said to be collinear (often misspelled as colinear). In greater generality, the term has been used for aligned objects, that is, things being “in a line” or “in a row”. (source: Wikipedia).

Removing collinear points is very useful when you have to deal with somehow generate polygons and you want to reduce their vertices, such as the result of an explosion in a destructible terrain or when you let the player draw on the screen.

Look at this example:

Draw something with the mouse in the upper half of the screen, I added a snap to grid effect to better let you see what happens, and see in real time your drawing in the bottom half of the screen once collinear points have been removed.

The script itself is very simple, most of the code is to generate the graphics and the snap to grid effect, anyway I highlighted the most interesting parts:

package {
	
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;

	public class Main extends Sprite {
		
		private var gridSize:Number=40;
		private var pointsVector:Vector.<Point>;
		private var canvas:Sprite;
		private var drawCanvas:Sprite;
		private var collinearCanvas:Sprite;
		
		public function Main() {
			canvas=new Sprite();
			addChild(canvas);
			canvas.graphics.lineStyle(1,0xdddddd);
			for (var i:Number=0; i<=640; i+=gridSize) {
				canvas.graphics.moveTo(i,0);
				canvas.graphics.lineTo(i,480);
			}
			for (i=0; i<=480; i+=gridSize) {
				canvas.graphics.moveTo(0,i);
				canvas.graphics.lineTo(640,i);
			}
			canvas.graphics.lineStyle(2,0x666666);
			canvas.graphics.moveTo(0,240);
				canvas.graphics.lineTo(640,240);
			drawCanvas=new Sprite();
			addChild(drawCanvas);
			collinearCanvas=new Sprite();
			collinearCanvas.y=240;
			addChild(collinearCanvas);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,startDrawing);
		}

		private function startDrawing(e:MouseEvent):void {
			pointsVector=new Vector.<Point>();
			var pen:Point=snapMouse(gridSize);
			pointsVector.push(pen);
			drawCanvas.graphics.clear();
			drawCanvas.graphics.lineStyle(1,0x880000);
			drawCanvas.graphics.drawCircle(pen.x,pen.y,5);
			drawCanvas.graphics.moveTo(pen.x,pen.y);
			stage.removeEventListener(MouseEvent.MOUSE_DOWN,startDrawing);
			stage.addEventListener(MouseEvent.MOUSE_UP,stopDrawing);
			stage.addEventListener(MouseEvent.MOUSE_MOVE,doDrawing);
		}

		private function stopDrawing(e:MouseEvent):void {
			stage.addEventListener(MouseEvent.MOUSE_DOWN,startDrawing);
			stage.removeEventListener(MouseEvent.MOUSE_UP,stopDrawing);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE,doDrawing);
		}

		private function doDrawing(e:MouseEvent):void {
			var pen:Point=snapMouse(gridSize);
			var lastPoint:Number=pointsVector.length-1;
			if (Math.abs(pen.x-pointsVector[lastPoint].x)+Math.abs(pen.y-pointsVector[lastPoint].y)==gridSize) {
				var newPoint:Boolean=true;
				for (var i:Number=0; i<=lastPoint; i++) {
					if (pen.x==pointsVector[i].x&&pen.y==pointsVector[i].y) {
						newPoint=false;
						break;
					}
				}
				if (newPoint) {
					pointsVector.push(pen);
					drawCanvas.graphics.lineStyle(2,0x000000);
					drawCanvas.graphics.lineTo(pen.x,pen.y);
					drawCanvas.graphics.lineStyle(1,0x880000);
					drawCanvas.graphics.drawCircle(pen.x,pen.y,5);
					drawCanvas.graphics.moveTo(pen.x,pen.y);
					traceCollinear();
				}
			}
		}

		private function traceCollinear():void {
			collinearCanvas.graphics.clear();
			collinearCanvas.graphics.lineStyle(1,0x880000);
			collinearCanvas.graphics.drawCircle(pointsVector[0].x,pointsVector[0].y,5);
			collinearCanvas.graphics.moveTo(pointsVector[0].x,pointsVector[0].y);
			for (var i:Number=1; i<pointsVector.length; i++) {
				if (i<pointsVector.length-1) {
					collinearCanvas.graphics.lineStyle(2,0x000000);
					collinearCanvas.graphics.lineTo(pointsVector[i].x,pointsVector[i].y);
					if (! isCollinear(pointsVector[i-1],pointsVector[i],pointsVector[i+1])) {
						collinearCanvas.graphics.lineStyle(1,0x880000);
						collinearCanvas.graphics.drawCircle(pointsVector[i].x,pointsVector[i].y,5);
						collinearCanvas.graphics.moveTo(pointsVector[i].x,pointsVector[i].y);
					}
				}
				else {
					collinearCanvas.graphics.lineStyle(2,0x000000);
					collinearCanvas.graphics.lineTo(pointsVector[i].x,pointsVector[i].y);
					collinearCanvas.graphics.lineStyle(1,0x880000);
					collinearCanvas.graphics.drawCircle(pointsVector[i].x,pointsVector[i].y,5);
					collinearCanvas.graphics.moveTo(pointsVector[i].x,pointsVector[i].y);
				}
			}
		}

		private function snapMouse(grid:Number):Point {
			return new Point(Math.round(mouseX/grid)*grid,Math.round(mouseY/grid)*grid);
		}

		private function isCollinear(p1:Point,p2:Point,p3:Point):Boolean {
			return (p1.y-p2.y)*(p1.x-p3.x)==(p1.y-p3.y)*(p1.x-p2.x);
		}
	}
}

Lines 109-111 (actually just line 110) determine if three points are collinear, that is lie on the same line.

Download the source code. Real world use of this feature next days.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers