void Start() { IsMove = false; mapData = new MapStruct() { Width = 30, Heigh = 15, }; layout = GetComponent <GridLayoutGroup> (); rectTrans = GetComponent <RectTransform> (); layout.constraintCount = mapData.Width; layout.cellSize = new Vector2(rectTrans.rect.size.x / mapData.Width, rectTrans.rect.size.y / mapData.Heigh); StartCoroutine(InitMap()); Dispatcher.RegisterProtocalListener("clickGrid", (o) => { Grid end = o[0] as Grid; curPlayer.curGrid.data.nextPoint = null; curPlayer.curGrid.data.lastPoint = null; end.data.nextPoint = null; end.data.lastPoint = null; A_Star a = new A_Star(gridObjs); a.FindPath(curPlayer.curGrid, end, false); curPlayer.curGrid = end; GridData cur = end.data; while (cur.lastPoint != null) { cur.lastPoint.nextPoint = cur; cur = cur.lastPoint; } while (cur != null) { cur.CurGrid.SetColor(); curPlayer.queue.Enqueue(cur); cur = cur.nextPoint; } IsMove = true; }); }
/// <summary> /// Generates waypoints using A* /// </summary> /// <param name="Position"></param> public virtual void Move(Vector2 Position, WorldHandler world) { Vector2 newPosition = new Vector2(); Vector2 selectedPosition = Position; float closestDistance = 0; if (Target != null && Target is IEntity) { for (int y = -1; y <= Target.Size.Y; y++) { for (int x = -1; x <= Target.Size.X; x++) { if (x == -1 || y == -1 || x == Target.Size.X || y == Target.Size.Y) { newPosition = Position + new Vector2(x, y); float currentDistance = Vector2.Distance(newPosition, this.Position); if (world.GetUnit(newPosition) == null && world.GetTile(newPosition) == null && (closestDistance == 0 || closestDistance > currentDistance)) { closestDistance = currentDistance; selectedPosition = newPosition; DistanceFromPosition = new Vector2(x, y); } } } } } waypoints.Clear(); waypoints = aStar.FindPath(this.Position, selectedPosition, world, waypoints); if (waypoints.Count > 0) { nextPoint = waypoints[0]; } else { nextPoint = Position; } TargetPosition = Position; }