AStarHelper.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class AStarHelper
  5. {
  6. public static AStarPoint getGoalFromGoal(AStarPoint start, AStarPoint end, AStarNode[,] nodes, Craft craft)
  7. {
  8. List<AStarNode> nodesList = getNodesLine(end, start, nodes);
  9. while(nodesList.Count > 0)
  10. {
  11. AStarNode node = nodesList[0];
  12. nodesList.RemoveAt(0);
  13. if(node.IsWalkable(craft))
  14. {
  15. return new AStarPoint(node.X, node.Y);
  16. }
  17. }
  18. return start;
  19. }
  20. public static AStarPoint getGoalFromStart(AStarPoint start, AStarPoint end, AStarNode[,] nodes, Craft craft)
  21. {
  22. List<AStarNode> nodesList = getNodesLine(start, end, nodes);
  23. AStarNode oldNode = nodes[start.x, start.y];
  24. while(nodesList.Count > 0)
  25. {
  26. AStarNode node = nodesList[0];
  27. nodesList.RemoveAt(0);
  28. if(!node.IsWalkable(craft))
  29. {
  30. break;
  31. }
  32. oldNode = node;
  33. }
  34. return new AStarPoint(oldNode.X, oldNode.Y);
  35. }
  36. private static List<AStarNode> getNodesLine(AStarPoint start, AStarPoint end, AStarNode[,] nodes)
  37. {
  38. int stepCount = 0;
  39. int fraction;
  40. int nextX = start.x;
  41. int nextY = start.y;
  42. int deltaX = end.x - nextX;
  43. int deltaY = end.y - nextY;
  44. int stepX;
  45. int stepY;
  46. AStarNode node;
  47. List<AStarNode> nodeList = new List<AStarNode>();
  48. if(deltaX < 0) stepX = -1; else stepX = 1;
  49. if(deltaY < 0) stepY = -1; else stepY = 1;
  50. deltaX = Math.Abs(deltaX*2);
  51. deltaY = Math.Abs(deltaY*2);
  52. if(deltaX > deltaY)
  53. {
  54. fraction = deltaY*2-deltaX;
  55. while(nextX != end.x)
  56. {
  57. if(fraction >= 0)
  58. {
  59. nextY = nextY+stepY;
  60. fraction = fraction-deltaX;
  61. }
  62. nextX = nextX+stepX;
  63. node = nodes[nextX, nextY];
  64. if(node != null)
  65. {
  66. nodeList.Add(node);
  67. }
  68. fraction = fraction+deltaY;
  69. stepCount++;
  70. }
  71. }
  72. else
  73. {
  74. fraction = deltaX*2-deltaY;
  75. while(nextY != end.y)
  76. {
  77. if(fraction >= 0)
  78. {
  79. nextX = nextX+stepX;
  80. fraction = fraction-deltaY;
  81. }
  82. nextY = nextY + stepY;
  83. node = nodes[nextX, nextY];
  84. if(node != null)
  85. {
  86. nodeList.Add(node);
  87. }
  88. fraction = fraction+deltaX;
  89. stepCount++;
  90. }
  91. }
  92. return nodeList;
  93. }
  94. }