var jarvisMarsh = function( p ){ const numPoints = 12; var vertices = []; var route = []; let iterations = 0; p.setup = function(){ p.createCanvas(750, 500); p.background(217); button = p.createButton('Reset Button') button.mousePressed(p.resetSketch); p.initValues(); } p.draw = function(){} p.drawLine = function(){ let r = p.findLeftPoint(); route[iterations] = r; p.findLeftLine(r); p.stroke(215, 75, 75); p.strokeWeight(1); for (var i = 0; i < route.length - 1; i++){ p.line(vertices[route[i]].x, vertices[route[i]].y, vertices[route[i+1]].x, vertices[route[i+1]].y) } } p.findLeftLine = function(originPoint){ var recordLeftVector = 1; let x1, x2, y1, y2; for (var i = 0; i < vertices.length; i++){ if (i != originPoint){ x1 = vertices[recordLeftVector].x - vertices[originPoint].x; y1 = vertices[recordLeftVector].y - vertices[originPoint].y; x2 = vertices[i].x - vertices[originPoint].x; y2 = vertices[i].y - vertices[originPoint].y; //if the result if positive then vector u is left of vector v //where u and v are both vectors from the target point //If its equal to 0 then they're colinear. This is also good :) if ((y2 * x1) - (y1 * x2) <= 0){ recordLeftVector = i; } } } if (originPoint != recordLeftVector && iterations < 75){ route[iterations] = recordLeftVector; iterations += 1; p.findLeftLine(recordLeftVector); } } p.findLeftPoint = function(){ let recordLeft = 0; for (var i = 0; i < vertices.length; i++){ if (vertices[i].x < vertices[recordLeft].x){ recordLeft = i; } } return recordLeft; } p.resetSketch = function(){ vertices.length = 0; p.clear() p.background(217); p.initValues(); p.findLeftLine(); p.draw(); } p.initValues = function(){ p.stroke(0); p.strokeWeight(7); var bufferx = p.width * 0.0625; var buffery = p.height * 0.0625; for (var i = 0; i < numPoints; i++){ vertices[i] = new dot(p.random(bufferx, p.width - bufferx), p.random(buffery, p.height - buffery)); p.point(vertices[i].x, vertices[i].y); } iterations = 0; p.drawLine(); } }; var myp5 = new p5(jarvisMarsh, 'c1');