int moveCost(Node_K source, Node_K target) { float zCost = Mathf.Abs(target.myCoord.y - source.myCoord.y); float xCost = Mathf.Abs(target.myCoord.x - source.myCoord.x); if (xCost > zCost) return Mathf.RoundToInt((14 * zCost) + 10*(xCost - zCost)); else return Mathf.RoundToInt((14 * xCost) + 10 * (zCost - xCost)); }
public void createAIArea() { areaOfNodes = new Node_K[numSpheresX,numSpheresZ]; Vector3 startingCorner = new Vector3(gameObject.GetComponent<Collider>().bounds.min.x,gameObject.transform.position.y, gameObject.GetComponent<Collider>().bounds.min.z); for (int x = 0; x < numSpheresX; x++) { for (int z = 0; z < numSpheresZ; z++) { Vector3 nodePos = startingCorner + new Vector3((nodeRadius * 2) * x + nodeRadius, 0.1f, (nodeRadius * 2) * z + nodeRadius); bool canWalk = !Physics.CheckSphere(nodePos, nodeRadius, obstacle); if(canWalk) areaOfNodes[x,z] = new Node_K(nodePos, canWalk, new Vector2(x,z),1); else areaOfNodes[x, z] = new Node_K(nodePos, canWalk, new Vector2(x, z),10000); } } }
public List<Node_K> neighbors(Node_K centerNode) { List<Node_K> neighborNodes = new List<Node_K>(); for (int x = -1; x < 2; x++) { for (int z = -1; z < 2; z++) { if (x == 0 && z == 0) continue; int xLimit = x + Mathf.RoundToInt(centerNode.myCoord.x); int zLimit = z + Mathf.RoundToInt(centerNode.myCoord.y); if (xLimit > -1 && zLimit > -1 && xLimit < numSpheresX && zLimit < numSpheresZ) neighborNodes.Add(areaOfNodes[xLimit, zLimit]); } } return neighborNodes; }
void createPath(Node_K target) { LinkedList<Node_K> path = new LinkedList<Node_K>(); Node_K node = target; while(node != null) { path.AddFirst(node); node = node.parent; } AIarea.fringePath = path; GameObject spherePath = GameObject.Find("SpherePathFringe"); if(spherePath.transform.FindChild("sphere")) { foreach (Transform child in spherePath.transform) Destroy(child.gameObject); } foreach (Node_K n in path) { GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere.layer = LayerMask.NameToLayer("black"); sphere.transform.parent = spherePath.transform; sphere.GetComponent<Renderer>().material.color = Color.black; sphere.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f); sphere.transform.position = n.myPos; } }
void reversePath(Node_K source, Node_K target) { List<Node_K> revPath = new List<Node_K>(); Node_K node = target; while(node != source) { revPath.Add(node); node = node.parent; } revPath.Reverse(); GameObject spherePath = GameObject.Find("SpherePathAStar"); if (spherePath.transform.FindChild("sphere")) { foreach (Transform child in spherePath.transform) Destroy(child.gameObject); } foreach (Node_K n in revPath) { GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere.layer = LayerMask.NameToLayer("red"); sphere.transform.parent = spherePath.transform; sphere.GetComponent<Renderer>().material.color = Color.red; sphere.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f); sphere.transform.position = n.myPos; } AIarea.aStarPath = revPath; }