// path finder AStar aStar; // world Vector nodes = new Vector(); // grid parameters, for drawing and interaction only int numRows; int numCols; float nodeHeight; float nodeWidth; // for mouse functions to set, to get path Node start; Node finish; void setup() { size(400,400); rectMode(CENTER); numCols = width/10; numRows = height/10; nodeWidth = width/(float)numCols; nodeHeight = height/(float)numRows; // initialise nodes and neighbours... createWorld(); // initialise aStar object with nodes aStar = new AStar(nodes); } void draw() { background(200); // draw nodes strokeWeight(1.0); stroke(220); for (Iterator iterator = nodes.iterator(); iterator.hasNext();) { Node n = (Node)iterator.next(); fill(n.walkable ? 255 : 230); rect(n.location,nodeWidth,nodeHeight); } // draw mouse node and neighbourhood if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { int mouseIndex = numCols*(numRows*mouseY/height)+(numCols*mouseX/width); Node n = (Node)nodes.get(mouseIndex); noStroke(); fill(255,0,0); rect(n.location,nodeWidth,nodeHeight); for (Iterator iterator = n.neighbours.iterator(); iterator.hasNext();) { Node n2 = (Node)iterator.next(); noStroke(); fill(255,0,0,80); rect(n2.location,nodeWidth,nodeHeight); } } // get path and draw it if (start != null && finish != null && start != finish && start.walkable && finish.walkable) { Vector path = aStar.getPath(start,finish); strokeWeight(nodeWidth); stroke(255,255,0,128); noFill(); beginShape(LINE_STRIP); for (Iterator iterator = path.iterator(); iterator.hasNext();) { Node n = (Node)iterator.next(); vertex(n.location.x,n.location.y); } endShape(); } } // drag and release to set a path // set start node void mousePressed() { if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { int mouseIndex = numCols*(numRows*mouseY/height)+(numCols*mouseX/width); start = (Node)nodes.get(mouseIndex); } } // set finish node void mouseDragged() { if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { int mouseIndex = numCols*(numRows*mouseY/height)+(numCols*mouseX/width); finish = (Node)nodes.get(mouseIndex); } } // set finish node void mouseReleased() { if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { int mouseIndex = numCols*(numRows*mouseY/height)+(numCols*mouseX/width); finish = (Node)nodes.get(mouseIndex); } } // convenience method void rect(Point p,float w,float h) { rect(p.x,p.y,w,h); }