// AStar example, based on TomC's astar_web, Aaron Steed 2006 import aStarLibrary.*; AStar aStar; int numRows; int numCols; float nodeHeight; float nodeWidth; Node start; Node finish; void setup() { size(400,400); rectMode(CENTER); numCols = 16; numRows = 16; nodeWidth = width/(float)numCols; nodeHeight = height/(float)numRows; // This is our AStar setup // A bit long but we want to get it right. aStar = new AStar(); // Set operation flags aStar.corners = true; aStar.manhattan = false; // Center it on screen and make a search web aStar.offset = new float [] { nodeWidth/2, nodeHeight/2, 0.0 }; aStar.makeCuboidNodes(new int [] { numCols, numRows } , nodeWidth); // Make some unwalkable nodes and then disconnect for(int i = 0; i < 30; i++){ Node n = (Node)aStar.nodes.get((int)random(aStar.nodes.size())); if(n.walkable){ n.walkable = false; } } aStar.radialDisconnectUnwalkables(); // Let's make the terrain a little lumpy by adding a third dimension // We have to modify all of the nodes or the pathfinder will crash. // What's interesting is that a high node is hard to get to but the other // high node next to it is easy to get to. Use your imagination and have fun. for(int i = 0; i < aStar.nodes.size(); i++){ Node n = (Node)aStar.nodes.get(i); n.p = n.addP(new float [] { 0.0, 0.0, random(nodeWidth * 10) } ); } } void draw() { background(50, 50, 250); stroke(0); strokeWeight(1); for(int i = 0; i < aStar.nodes.size(); i++){ Node n = (Node)aStar.nodes.get(i); if(n.walkable){ fill(50 + (200 / (nodeWidth * 10)) * n.z()); rect(n.x(), n.y(), 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(); for (int i = 0; i < path.size(); i++){ Node n = (Node)path.get(i); vertex(n.x(),n.y()); } endShape(); } } // 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)aStar.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)aStar.nodes.get(mouseIndex); } } // create an unwalkable node void keyPressed() { if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { int mouseIndex = numCols*(numRows*mouseY/height)+(numCols*mouseX/width); Node n = (Node)aStar.nodes.get(mouseIndex); n.walkable = false; } }