public static void run(String[] args) { Logger log = new Logger(); Stopwatch s = new Stopwatch(); log.addToLog("Map initializing..."); AStarMap map = new AStarMap(mapData.getMapWidth(), mapData.getMapHeight(), mapData.getObstacleMap()); log.addToLog("Heuristic initializing..."); //AStarHeuristic heuristic = new ClosestHeuristic(); AStarHeuristic heuristic = new DiagonalHeuristic(); log.addToLog("AStar initializing..."); AStar aStar = new AStar(map, heuristic); log.addToLog("Calculating shortest path..."); s.Start(); List<Point> shortestPath = aStar.calcShortestPath(startX, startY, goalX, goalY); s.Stop(); log.addToLog("Time to calculate path in milliseconds: " + s.ElapsedMilliseconds); log.addToLog("Printing map of shortest path..."); new PrintMap(map, shortestPath); }
public List<AStarNode> RunAStar(WorldState currentWorldState) { AStarNode startNode = new AStarNode(); AStarNode endNode = new AStarNode(); startNode.SetWorldState(goalWorldState); endNode.SetWorldState(currentWorldState); AStar star = new AStar(); List<AStarNode> plan = star.Run(startNode, endNode); //används under utvecklingsfasen /*Debug.Log("HÄR ÄR PLANEN!!!!!!!!: " + plan.Count); foreach(AStarNode node in plan) { Debug.Log(node.name); }*/ //---------------------------- /*foreach(AStarNode node in plan) { //TODO: dubbelkolla att returnerande action faktiskt finns blackBoard.setCurrentAction(node.name); }*/ //blackBoard.setCurrentAction(""); return plan; }
public void Awake() { time = Time.time; Loaded = false; mGen = GetComponent<MapGeneration> (); //new MapGeneration(); pFind = GetComponent<AStar> (); photonView = GetComponent<PhotonView> (); seed = 0; if (PhotonNetwork.isMasterClient) { seed = Random.seed; for (int i = -4; i <= 4; ++i) { for(int j = -4; j <= 4; ++j){ mGen.GenerateBlock (i, j, seed, 0, 0); } } mGen.CreateGrid(0, 0); Loaded = true; lastX = 0; lastY = 0; } // in case we started this demo with the wrong scene being active, simply load the menu scene if (!PhotonNetwork.connected) { Application.LoadLevel(Menu.SceneNameMenu); return; } // we're in a room. spawn a character for the local player. it gets synced by using PhotonNetwork.Instantiate playerObject = PhotonNetwork.Instantiate(this.playerPrefab.name, transform.position, Quaternion.identity, 0); playerController = playerObject.GetComponent<ThirdPersonController> (); }
public void AStarSearchTestFirstMap() { char[,] map = { { '-', '-', '-', '-', '-' }, { '-', '-', '*', '-', '-' }, { '-', 'W', 'W', 'W', '-' }, { '-', '-', '-', '-', '-' }, { '-', '-', 'P', '-', '-' }, { '-', '-', '-', '-', '-' } }; var aStar = new AStar(map); var cells = aStar.FindShortestPath(new int[] { 4, 2 }, new int[] { 1, 2 }); Assert.AreEqual(cells.Count, 5); Assert.AreEqual(cells[0][0], 1, "An expected cell in the path did not match!"); Assert.AreEqual(cells[0][1], 2, "An expected cell in the path did not match!"); Assert.AreEqual(cells[1][0], 1, "An expected cell in the path did not match!"); Assert.AreEqual(cells[1][1], 3, "An expected cell in the path did not match!"); Assert.AreEqual(cells[2][0], 2, "An expected cell in the path did not match!"); Assert.AreEqual(cells[2][1], 4, "An expected cell in the path did not match!"); Assert.AreEqual(cells[3][0], 3, "An expected cell in the path did not match!"); Assert.AreEqual(cells[3][1], 3, "An expected cell in the path did not match!"); Assert.AreEqual(cells[4][0], 4, "An expected cell in the path did not match!"); Assert.AreEqual(cells[4][1], 2, "An expected cell in the path did not match!"); }
/// <summary> /// creates empty NPC with placeholder attributes /// </summary> /// <param name="Content"></param> /// <param name="graphicsDevice"></param> /// <param name="world"></param> /// <param name="bilbo"></param> public NPC(ContentManager Content, GraphicsDevice graphicsDevice, World world, BillboardEngine bilbo, AudioManager audio) { model = null; position = Vector3.Zero; direction = Vector3.Zero; this.world = world; speed = 0; level = 0; maxHealth = 0; health = 0; active = false; newTarget = false; XP = 0; cooldown = 0; maxCooldn = 0; element = 0; kind = 0; strength = 0; pathFinder = null; target = Vector3.Zero; isHit = false; hitTimer = 0; isDead = false; billboardEngine = bilbo; this.graphicsDevice = graphicsDevice; this.audio = audio; explosion = new Explosion(Position, graphicsDevice, Content); dmgNumbers = new List<DmgNumber>(); }
public override void BeginPerform(Order order) { shouldGoToBed = false; // Abort previous surgery RemoveFromSurgery(); /* // Is this a surgery? currentBed = order.objectAction as Bed; OrBed orBed = currentBed as OrBed; if (orBed != null) { if (orBed.nurse != null) { return; } orBed.nurse = this; } */ // Pathfinding! Vector3 pos = transform.position; Vector3 objectPos = order.objectAction.transform.position; AStar astar = new AStar(); currentPath = astar.FindPath(pos, objectPos); currentBed = order.objectAction as Bed; }
public void Awake() { //instanciates A* implemenation with defined heuristics //IPathHeuristic heuristic = new EuclideanPathHeuristic(new ObstaclesDensityPathHeuristic()/*, (a, b) => a*b/2*/); pathFinder = new AStar(/*heuristic*/); IsGoalDefined = false; timeOfLastSubGoalLookAhead = Time.time; }
public void Move() { foreach(Transform pathingline in pathinglines) { Destroy(pathingline.gameObject); } pathinglines.Clear(); if (heading != null) { if (cell != heading) { AStar pathFinder = new AStar(); pathFinder.FindPath(cell, heading, cell.GetComponentInParent<Board>().board, false); List<Cell> path = pathFinder.CellsFromPath(); if (path.Count > 0) { pendingmove = path[0]; } else { Debug.LogWarning("Target location is unreachable"); // IF this is our job clear it if (job != null) { if (job.GetComponent<Cell>().Equals(heading)) { job = null; } } heading = cell; } } } if (pendingmove != null) { if (cell != pendingmove) { Debug.LogWarning("Pending move didn't match position"); cell = pendingmove; if (job != null) { if (job.GetComponent<Cell>().Equals(pendingmove)) { job = null; } } } } }
void Start () { a = GetComponent<AStar>(); view = GetComponent<GameView>(); a.Init(row, col, startPos, endPos); a.PutObstacle(obstaclePos); view.ShowMap(); // view.ShowSearchPath(); }
public Queue<Vector2> GetPath(Vector2 start, Vector2 goal) { if (graph.nodes == null) { BuildGraph(); astar = new AStar(graph); } Vector2 begin = new Vector2(Mathf.Round(start.x), Mathf.Round(start.y)); return astar.GetPath(graph.nodes[begin], graph.nodes[goal]); }
public PRM(Vector3 bounds, OccupancyGrid occupancy, float radius, int neighbours, ConnectionMethod method) { graph = new StateConfGraph(); this.bounds = bounds; this.occupancy = occupancy; this.radius = radius; this.neighbours = neighbours; this.method = method; this.search = new AStar(); }
// Use this for initialization void Start () { GameObject backgd = GameObject.Find ("background"); //调用脚本background中的地图 bg = (background16)backgd.GetComponent (typeof(background16)); GameObject moneyobj = GameObject.Find ("enemy"); //调用脚本background中的地图 monkeyscript = (monkey16)moneyobj.GetComponent (typeof(monkey16)); astar = new AStar(); animator = GetComponent<Animator> (); hasdone = 1; }
public void UpdateGraph(Vector2 point) { if (graph.nodes == null) { BuildGraph(); astar = new AStar(graph); return; } MapData data = MapController.Instance.mapData; List<Vector2> neighbors = data.GetNeighbors(point); TileType type = data.tileData[(int)point.x, (int)point.y]; if (!type.walkable) // Tile became unwalkable { Node deleting = graph.nodes[point]; graph.nodes.Remove(point); List<Node> notDiagNeighbors = new List<Node>(); Node nei; foreach (Vector2 neighbor in neighbors) { if (graph.nodes.TryGetValue(neighbor, out nei)) { graph.nodes[neighbor].edges.Remove(deleting); bool diag = (point.x - neighbor.x) * (point.y - neighbor.y) != 0f; if (!diag) notDiagNeighbors.Add(graph.nodes[neighbor]); } } // In order to avoid diagonal moves near unwalkable tiles. foreach (Node n in notDiagNeighbors) { foreach (Node n2 in notDiagNeighbors) { n.edges.Remove(n2); } } } else // Tile is walkable. Need to change edges { if (!graph.nodes.ContainsKey(point)) { graph.nodes.Add(point, new Node(point)); } Node n = graph.nodes[point]; Node nei; foreach (Vector2 neighbor in neighbors) { if (graph.nodes.TryGetValue(neighbor, out nei)) { n.edges[nei] = 1 / data.tileData[(int)neighbor.x, (int)neighbor.y].speed; nei.edges[n] = 1 / data.tileData[(int)n.place.x, (int)n.place.y].speed; } } } }
// Use this for initialization void Start () { var grid = new SqaureGrid(width, height); assembleWalls(grid); assembleRoads(grid); assembleForests(grid); //randomise start and destination if (randomGen) { bool isGenerated = false; int randStartX = (int)startVec.x; int randStartY = (int)startVec.y; while (!isGenerated) { if (!isSeamless) { randStartX = Random.Range(0, width); randStartY = Random.Range(0, height); } int randDestX = Random.Range(1, width); int randDestY = Random.Range(1, height); if(!grid.walls.Contains(new Location(randStartX, randStartY)) && !grid.walls.Contains(new Location(randDestX, randDestY))) { startVec = new Vector2(randStartX, randStartY); destinationVec = new Vector2(randDestX, randDestY); isGenerated = true; } } } //set locations Location start = new Location((int)startVec.x, (int)startVec.y); Location destination = new Location((int)destinationVec.x, (int)destinationVec.y); transform.position = new Vector3(startVec.x, transform.position.y, startVec.y); var astar = new AStar(grid, start, destination); route = generatePath(grid, astar, destination, start); drawBorder(); drawGrid(grid, astar, route); routePos = route.First; distance = 1.2f; //set first person camera in active fpCamera = this.transform.FindChild("Camera").GetComponent<Camera>(); fpCamera.gameObject.SetActive(false); //set movement slider movementSlider = GameObject.FindGameObjectWithTag("movementSlider").GetComponent<Slider>(); isDone = false; }
public override void BeginPerform(Order order) { shouldGoToBed = false; isInBed = false; RemoveFromSurgery(); transform.rotation = Quaternion.identity; currentBed = order.objectAction as Bed; AStar astar = new AStar(); currentPath = astar.FindPath(transform.position, order.objectAction.transform.position); }
public override void BeginPerform(Order order) { shouldGoToBed = false; RemoveFromSurgery(); currentBed = order.objectAction as Bed; Vector3 pos = transform.position; Vector3 objectPos = order.objectAction.transform.position; AStar astar = new AStar(); currentPath = astar.FindPath(pos, objectPos); }
/* //=============================角色動作============================= public Animator Anim; public AnimatorStateInfo BS; static int Idle = Animator.StringToHash("Base.Layer.BG_Chibi_Idle"); static int Run = Animator.StringToHash("Base.Layer.BG_Chibi_B_Run"); static int Attac = Animator.StringToHash("Base.Layer.0G_Chibi_Attack00"); static int Skill = Animator.StringToHash("Base.Layer.0G_Chibi_Attack00"); public enum eEgo { None = -1, Idle, Run, Attac, Skill } public eEgo iNowEgo = eEgo.None; //=============================完============================= */ void Awake(){ //iNowEgo = eEgo.Idle; m_Instance = this; //獲得AStar的Component //Camera mainCamera = Camera.main; //m_AStar = mainCamera.GetComponent<AStar>(); m_AStar = this.GetComponent<AStar> (); //m_AIData初始化 m_AIData.fspeed = 0.1f; m_AIData.fMaxspeed = m_fMaxSpeed; m_AIData.frotate = 0.0f; m_AIData.fMaxrotate = 10.0f; m_AIData.fColProbe = 1.0f; m_AIData.thisPoint = this.gameObject; m_AIData.targetPoint = targetPoint; m_AIData.m_Obs = SceneManager.m_Instance.m_Obs; m_AIData.fRadius = 0.5f; m_AIData.iAstarIndex = -1; m_AIData.targetPosition = Vector3.zero; m_AIData.fDetectLength = 10.0f; m_AIData.fAttackLength = 5.0f; m_AIData.fAttack = 10.0f; m_AIData.fSkill = 30.0f; m_AIData.fSkillMP = 20.0f; m_AIData.iEXPGET = 20; m_AIData.fHP = fHP; m_AIData.fMP = fMP; m_AIData.fMaxHP = fMaxHP; m_AIData.fMaxMP = fMaxMP; /* 生成隊長時呼叫自己的小兵,並傳入變數給小兵,指派他的隊長 */ //FSM的設定 m_FSMManager = new FSMManager (); FSMNpcIdleState IdleState = new FSMNpcIdleState (); FSMNpcTrackState TrackState = new FSMNpcTrackState (); FSMNpcAttackState AttackState = new FSMNpcAttackState (); FSMNpcSkillState SkillState = new FSMNpcSkillState (); IdleState.AddTransition (eTransitionID.Idle_To_Track, eStateID.Track); TrackState.AddTransition (eTransitionID.Track_To_Attack, eStateID.Attack); TrackState.AddTransition (eTransitionID.Track_To_Skill, eStateID.Skill); AttackState.AddTransition (eTransitionID.Attack_To_Idle, eStateID.Idle); AttackState.AddTransition (eTransitionID.Attack_To_Track, eStateID.Track); SkillState.AddTransition (eTransitionID.Skill_To_Idle, eStateID.Idle); SkillState.AddTransition (eTransitionID.Skill_To_Track, eStateID.Track); m_FSMManager.AddState (IdleState); m_FSMManager.AddState (TrackState); m_FSMManager.AddState (AttackState); m_FSMManager.AddState (SkillState); m_AIData.m_State = m_FSMManager; }
public Program() { Current = SquarePuzzle.CreateLinear(3); SquarePuzzle.Shuffle(Current, 10); // even a small shuffle can result in huge search times Goal = SquarePuzzle.CreateLinear(3); Console.WriteLine("Starting position:"); Current.Print(); Console.WriteLine("Goal position:"); Goal.Print(); aStar = new AStar(Current, Goal); }
// Use this for initialization void Start () { _grid = new Grid(50,30); _grid.SetStartNode(0,2); _grid.SetEndNode(48,10); astar = new AStar(); if(astar.findPath(_grid)) { for(int i = 0; i<astar._path.Count;i++) { text += "("+astar._path[i].x+","+astar._path[i].y+")"+" "; } Debug.Log(text); } }
public void TestGetPath() { int[,] grid = new int[9, 9]; grid[4, 3] = 1; grid[4, 4] = 1; grid[4, 5] = 1; Point start = new Point(2, 4); Point end = new Point(6, 4); AStar aStar = new AStar(); var path = aStar.GetPath(grid, start, end); Assert.AreEqual(9, path.Count); var reversePath = aStar.GetPath(grid, end, start); Assert.AreEqual(9, reversePath.Count); }
// Use this for initialization void Start() { m_AStar = this.GetComponent<AStar>(); ; //m_AIData初始化 m_AIData.fspeed = 20.0f; m_AIData.fMaxspeed = m_fMaxSpeed; m_AIData.frotate = 0.0f; m_AIData.fMaxrotate = 10.0f; m_AIData.fColProbe = 2.0f; m_AIData.thisPoint = this.gameObject; m_AIData.targetPoint = targetPoint; m_AIData.m_Obs = SceneManager.m_Instance.m_Obs; m_AIData.m_Wall = SceneManager.m_Instance.m_Wall; m_AIData.fRadius = 0.5f; m_AIData.iAstarIndex = -1; m_AIData.targetPosition = Vector3.zero; m_AIData.fDetectLength = 20.0f; m_AIData.fAttackLength = 10.0f; m_AIData.fHP = 100.0f; m_AIData.fMP = 30.0f; m_AIData.fAttack = 10.0f; m_AIData.fSkill = 30.0f; //FSM的設定 m_FSMManager = new FSMManager(); FSMIdleState IdleState = new FSMIdleState(); //FSMTrackState TrackState = new FSMTrackState (); //FSMChaseState ChaseState = new FSMChaseState (); //FSMAttackState AttackState = new FSMAttackState (); //FSMWanderState WanderState = new FSMWanderState (); //IdleState.AddTransition (eTransitionID.Idle_To_Track, eStateID.Track); //IdleState.AddTransition (eTransitionID.Idle_To_Chase, eStateID.Chase); //IdleState.AddTransition (eTransitionID.Idle_To_Attack, eStateID.Attack); //IdleState.AddTransition (eTransitionID.Idle_To_Wander, eStateID.Wander); //TrackState.AddTransition (eTransitionID.Track_To_Idle, eStateID.Idle); //TrackState.AddTransition (eTransitionID.Track_To_Chase, eStateID.Chase); //TrackState.AddTransition (eTransitionID.Track_To_Attack, eStateID.Attack); //TrackState.AddTransition (eTransitionID.Track_To_Wander, eStateID.Wander); //ChaseState.AddTransition (eTransitionID.Chase_To_Attack, eStateID.Attack); //ChaseState.AddTransition (eTransitionID.Chase_To_Idle, eStateID.Idle); //AttackState.AddTransition (eTransitionID.Attack_To_Idle, eStateID.Idle); //AttackState.AddTransition (eTransitionID.Attack_To_Chase, eStateID.Chase); //WanderState.AddTransition (eTransitionID.Wander_To_Idle, eStateID.Idle); m_FSMManager.AddState(IdleState); //m_FSMManager.AddState (TrackState); //m_FSMManager.AddState (ChaseState); //m_FSMManager.AddState (AttackState); //m_FSMManager.AddState (WanderState); m_AIData.m_State = m_FSMManager; }
public static void Main(string[] args) { var grid = new Grid2D(20, 20, 25, 0, 0, 19, 19); var astar = new AStar(grid.Start, grid.Goal); var result = astar.Run(); Console.WriteLine(result); var output = grid.Print(astar.GetPath()); Console.WriteLine(output); Console.ReadLine(); }
public LD_Dungeon(int width, int height, double seed,Vector2 returnSpot) { this.seed = seed; r = new RandomSeed(seed); this.width = width; this.height = height; type = LevelData.TYPE_DUNGEON; astar = new AStar(this.width, this.height); this.parentStartLocation = returnSpot; this.fogClearRadius = r.getIntInRange(4,6); COLLISION = AsciiMapSymbols.MOUNTAIN; }
public void InitGame()//初始化寻路网格 { hasdone = 1; astar = new AStar(); animator = GetComponent<Animator> (); for (int i =0; i< 14; i++) {//初始化地图是否可走 for (int j =0; j< 10; j++) { if(bg.level13.map [i, j]!= 0) grid.SetWalkbale(i,j,false); else grid.SetWalkbale(i,j,true); } } grid.SetStartNode (13,0); grid.SetEndNode (7,5); }
//private static char[,] map = //{ // { '-', '-', '-', '-', '-' }, // { '-', '-', '*', '-', '-' }, // { '-', 'W', 'W', 'W', '-' }, // { '-', '-', '-', '-', '-' }, // { '-', '-', 'P', '-', '-' }, // { '-', '-', '-', '-', '-' } // }; //private static char[,] map = //{ // { '-', '-', '-', '-', 'W', '-', '-', '-', 'W', '*', '-' }, // { '-', 'W', '-', '-', 'W', '-', '-', '-', 'W', '-', '-' }, // { 'P', '-', 'W', '-', 'W', '-', '-', '-', 'W', '-', '-' }, // { '-', 'W', '-', '-', 'W', 'W', 'W', '-', 'W', 'W', '-' }, // { '-', '-', '-', 'W', 'W', '-', '-', '-', '-', 'W', '-' }, // { '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-' } //}; static void Main() { var playerCoords = FindObjectCoordinates('P'); var destinationCoords = FindObjectCoordinates('*'); var aStar = new AStar(map); var cells = aStar.FindShortestPath(playerCoords, destinationCoords); foreach (var cellInPath in cells) { var row = cellInPath[0]; var col = cellInPath[1]; map[row, col] = '@'; } PrintMap(); }
public LD_Cave(int width, int height, double seed,Vector2 returnSpot) { this.seed = seed; r = new RandomSeed(seed); this.width = width; this.height = height; type = LevelData.TYPE_CAVE; astar = new AStar(this.width, this.height); this.startLocation = new Vector2(width/2, height/2); // START IN THE MIDDLE? this.parentStartLocation = returnSpot; this.fogClearRadius = r.getIntInRange(2,5); COLLISION = AsciiMapSymbols.MOUNTAIN; //this.isFoggy = false; }
/// <summary> /// Initializes a new instance of the <see cref="PlayBoard"/> class. /// </summary> /// <param name="width">Width of board</param> /// <param name="height">Height of board</param> public PlayBoard(int width, int height){ _powerShards = new List<PowerShard>(); _width = width; _height = height; _grid = new List<List<Hexagon>>(); _grid.Capacity = (int)width; for (var i = 0; i < width; ++i) { List<Hexagon> list = new List<Hexagon> (); list.Capacity = (int)height; for (var j = 0; j < height; ++j) { list.Add(new Hexagon(-1,-1, this)); } _grid.Add(list); } _astar = new AStar<Hexagon>(); _portals = new List<Portal>(); }
public LevelData(int width,int height, double seed, int theType) { this.seed = seed; r = new RandomSeed(seed); //SET THE COLOR FOR MY ASCII TEXT THING UColor.HSL theMainColor = new UColor.HSL((float)r.getRandom(),0.7f,0.3f); //Choose a main color MainColor = theMainColor.toColor(); this.width = width; this.height = height; type = theType; md = new AsciiMapSymbols(type, MainColor); astar = new AStar(this.width, this.height); this.startLocation = new Vector2(width/2, height/2); this.parentStartLocation = startLocation; clearTo(0); }
public List<Point> GetPath(Point from, Point to, NavMesh navMesh) { List<Point> path = new List<Point>(); // First find the polygon they're in // !* May want a little overlapping so all screen can be clicked. // In that case this should check if all intersected options contain as same poly start/end ConvexPolygon polyStart = navMesh.PolygonList.First(x => x.Intersects(from)); ConvexPolygon polyEnd = navMesh.PolygonList.First(x => x.Intersects(to)); if (polyStart == null || polyEnd == null) { return path; } else if (polyStart == polyEnd) { path.Add(from); path.Add(to); } else if (polyStart != polyEnd) { // This does not need doing every time but it's easier to code if is recreated. _astar = new AStar<NavigationNode>( delegate(NavigationNode startNode, NavigationNode endNode) { return Math.Sqrt(startNode.Position.X * endNode.Position.X + startNode.Position.Y * endNode.Position.Y); }); var startEndNodes = CreateNodeNetwork(polyStart, polyEnd, from, to, navMesh); _astar.FindPath(startEndNodes.Item1, startEndNodes.Item2); _astar.Path.Reverse(); foreach (var node in _astar.Path) { path.Add(node.Position); } } return path; }
public PseudoLinearLevel(uint levelWidth, uint levelHeight, uint numberOfLG_Rooms, uint minLG_RoomWidth, uint maxLG_RoomWidth, uint minLG_RoomHeight, uint maxLG_RoomHeight, uint theTileWidth, uint theTileHeight, RandomSeed randSeed = null, uint roomSpacing = 3) { if(randSeed == null) { r = new RandomSeed(DateTime.Now.Millisecond); } else { r = randSeed; }//else rooms = new System.Collections.Generic.List<LG_Room>(); borderThickness = (uint)roomSpacing; rooms_sorted = new System.Collections.Generic.Dictionary<Vector2, LG_Room>(); roomCenterPoints = new System.Collections.Generic.List<Vector2>(); roomConnections = new System.Collections.Generic.List<Edge>(); tileWidth = theTileWidth; tileHeight = theTileHeight; //super(levelWidth, levelHeight); width = (int)levelWidth; height = (int)levelHeight; //AStar.grid_width = tileWidth; //AStar.grid_height = tileHeight; astar = new AStar(width, height); initializeBitmap(1); placeLG_Rooms((int)minLG_RoomWidth, (int)maxLG_RoomWidth, (int)minLG_RoomHeight, (int)maxLG_RoomHeight, (int)numberOfLG_Rooms); digHallways(); //findStartAndEnd(); //findCriticalPath(); setupAstar(); doSetupLogic(); }
public void Update(float deltaTime) { // TODO: pathfinding // If we have a next tile, move to it if (jobReached == false && DestTile != CurrTile) { // We have some place to be // Do we have pathfinding already? if (pathfinding == null) { // If not we should find new pathfinding. pathfinding = new AStar(DestTile.world.Graph, CurrTile, DestTile); } if (CurrTile == NextTile) // We moved another step in the right direction // If this is the first step on our journey it's fine because we just generated a path. // We might not just be moving inside of a room, but on the world scale { NextTile = pathfinding.DequeueNextTile(); if (NextTile == null) // The pathfinding does not know where to go. Delete the current job, since only a job can make a character move { Debug.Log("Deleting job"); CurrentJob.DeleteJob(); return; } } // MOVEMENT // We have a place to be, update our movement, lets assume that next tile is always 1 distance unit away // Can we move to the next tile? if (NextTile.IsEnterable()) { ProgressToNextTile += deltaTime * Speed; if (ProgressToNextTile >= 1) { // We have reached the next tile! CurrTile = NextTile; ProgressToNextTile = 0; } } OnCharacterPositionChanged(this); } else { // We have reached our destination :) // do work on the current job if (CurrentJob != null) { // This is also where we gain experience for the work done Skills jobSkill = CurrentJob.GetJobType(); float skillLvl = stats[jobSkill]; CurrentJob.DoWork(this, deltaTime); // Xp gained is based on time spent working, so more work (due to higher level) doesn't equal more xp float xpAmount = deltaTime / (skillLvl * 60); stats[jobSkill] += xpAmount; } // If we don't have a job look for one if (CurrentJob == null) { // Request a job from the world // TODO: subclass this so different characters can request different jobs // TODO: this gets spammed if there are no jobs, perhaps make the character idle for a couple seconds? Could also be a job! // TODO: move this request into the job queue, should probably pass your own preferences of jobs in that function too Job j = world.Jobs.RequestJob(jobPriorities); OverrideJob(j); if (CurrentJob == null) { // No job available for the moment, so lets just return and do nothing // TODO: make the character do something? return; } } } }
public static void GeneratePath() { finalPath = AStar.GetPath(UnitSpawnTile.GridPosition, UnitDespawnTile.GridPosition); }
public override void OnExecute(float dt) { bool seeEnemy = canSeeEnemy(); if (!sawEnemy && seeEnemy) { Node[] thePath = AStar.getPath(AStar.findNearestNode(theEnemy.position), AStar.findNearestTargetNode(theTransform.position, theEnemy.position)); currentIndex = 0; path = thePath; Reached = false; sprinter.startSprinting(); } if (Reached) { return; } Vector3 toDestination = path[currentIndex].theTransform.position - theTransform.position; toDestination.y = 0.0f; Vector3 movement = toDestination.normalized * sprinter.currentSpeed * dt; if (movement.magnitude > toDestination.magnitude) { movement = toDestination; } theTransform.position += movement; Vector3 firstPosition = theTransform.position; Vector3 secondPosition = path[currentIndex].theTransform.position; firstPosition.y = 0.0f; secondPosition.y = 0.0f; if (firstPosition == secondPosition) { ++currentIndex; Reached = currentIndex == path.Length; } sawEnemy = seeEnemy; }
public void FindPath() { NativeHashMap <int2, bool> isObstacle = new NativeHashMap <int2, bool>(obstacles.Count, Allocator.TempJob); NativeArray <int2> offsets = new NativeArray <int2>(8, Allocator.TempJob); NativeArray <Node> startNative = new NativeArray <Node>(starts.Count, Allocator.TempJob); NativeMultiHashMap <int2, Node> results = new NativeMultiHashMap <int2, Node>(starts.Count * safeGuard, Allocator.TempJob); foreach (int2 o in obstacles.Keys) { isObstacle.Add(o, true); } int counter = 0; foreach (Node n in starts.Values) { startNative[counter] = n; counter++; } offsets[0] = new int2(0, 1); offsets[1] = new int2(1, 1); offsets[2] = new int2(1, 0); offsets[3] = new int2(1, -1); offsets[4] = new int2(0, -1); offsets[5] = new int2(-1, -1); offsets[6] = new int2(-1, 0); offsets[7] = new int2(-1, 1); AStar aStar = new AStar { isObstacle = isObstacle, offsets = offsets, startNative = startNative, results = results, end = end, safeGuard = safeGuard }; JobHandle handle = aStar.Schedule(starts.Count, 16); handle.Complete(); NativeKeyValueArrays <int2, Node> keyValueArray = results.GetKeyValueArrays(Allocator.Temp); Dictionary <int2, Queue <Node> > waypoints = new Dictionary <int2, Queue <Node> >(); for (int i = 0; i < keyValueArray.Keys.Length; i++) { if (!waypoints.ContainsKey(keyValueArray.Keys[i])) { waypoints.Add(keyValueArray.Keys[i], new Queue <Node>()); waypoints[keyValueArray.Keys[i]].Enqueue(keyValueArray.Values[i]); } else { waypoints[keyValueArray.Keys[i]].Enqueue(keyValueArray.Values[i]); } } foreach (int2 start in waypoints.Keys) { StartCoroutine(MoveUnitCoroutine(start, waypoints[start])); } startNative.Dispose(); isObstacle.Dispose(); offsets.Dispose(); results.Dispose(); }
void Update() { if (waiting || gameOver || !modeSelected) { return; } if (player == 1 && computerPlayer) { if (ai.go()) { endPhase(); } checkGameOver(); return; } if (!Input.mousePresent) { mouse = null; } else { HexPosition newMouse = getMouseHex(); if (newMouse == null) { HexPosition.clearSelection("Path"); HexPosition.clearSelection("Attack"); path = null; } else { if (newMouse != mouse) { if (mouse != null) { mouse.unselect("Cursor"); } if (newMouse.containsKey("Obstacle")) //The Obstacle tag is being used to make the tile unselectable. { if (mouse != null && phase == Phase.MOVE) { HexPosition.clearSelection("Path"); HexPosition.clearSelection("Attack"); path = null; } mouse = null; return; } mouse = newMouse; //display where the cursor is pointing at mouse.select("Cursor"); //if is in move phase, also display the route toward where the cursor is current at if (phase == Phase.MOVE) { Unit unit = selection.getUnit(); HexPosition.clearSelection("Path"); HexPosition.clearSelection("Attack"); path = AStar.search(selection, mouse, unit.SPEED); HexPosition.select("Path", path); } } if (Input.GetMouseButtonDown(0)) { switch (phase) { case Phase.SELECT: select(); break; case Phase.MOVE: move(); break; case Phase.ATTACK: attack(); break; default: print("Error: Turn " + phase + " not implemented."); break; } return; } else if (Input.GetMouseButtonDown(1)) { HexPosition.clearSelection("Path"); HexPosition.clearSelection("Attack"); HexPosition.clearSelection("Movable"); HexPosition.clearSelection("Selection"); phase = Phase.SELECT; Unit unit = selection.getUnit(); unit.undoMovement(moveFromPos); unit.setState(Unit.State.MOVE); selectSelectable(); } } } }
void CommandUpdate() { switch (command) { case COMMAND.NONE: break; case COMMAND.MOVE: { if (prevCommand != COMMAND.MOVE) { getActiveGirds.Clear(); if (gridSelect != null) { gridSelect.gameObject.SetActive(false); } } #region showMoveRange VectorInt2 _playerVi = player.StandGrid.Vi; VectorInt2[] _moveViArray = Util.GetViCricleByRadius(player.playerData.speed); getActiveGirds.Clear(); foreach (var _moveVi in _moveViArray) { VectorInt2 _resultMoveVi = _playerVi + _moveVi; if (_resultMoveVi < VectorInt2.Zero || _resultMoveVi > (map.Edge - VectorInt2.One)) { continue; } if (map.gridMat [_resultMoveVi.x, _resultMoveVi.y] is BuildGrid) { continue; } getActiveGirds.Add(map.gridMat[_resultMoveVi.x, _resultMoveVi.y]); map.gridMat [_resultMoveVi.x, _resultMoveVi.y].SetGridColor(Color.blue); } #endregion //ray cast Ray _ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit _hit = new RaycastHit(); if (Physics.Raycast(_ray, out _hit, 1000f)) { Grid _grid = _hit.collider.GetComponentInParent <Grid> (); if (_grid == null) { break; } if (!getActiveGirds.Contains(_grid)) { break; } if (gridSelect != null) { gridSelect.gameObject.SetActive(true); gridSelect.transform.position = _grid.transform.position; } if (_grid.Owner == null) { getMoveGrids = AStar.CalcPath(player.StandGrid, _grid, map); //press mouse button 0 if (Input.GetMouseButtonDown(0)) { if (EventSystem.current.IsPointerOverGameObject()) { break; } if (gridSelect != null) { gridSelect.gameObject.SetActive(false); } command = COMMAND.DOING; //move player MovePlayer(player, getMoveGrids); break; } } } } break; case COMMAND.ATTACK: { if (prevCommand != COMMAND.ATTACK) { getActiveGirds.Clear(); if (gridSelect != null) { gridSelect.gameObject.SetActive(false); } } if (map != null && player.StandGrid != null) { #region show AttackRange //获得玩家所在grid的坐标 VectorInt2 _playerVi = player.StandGrid.Vi; VectorInt2[] _attackViArray = Util.GetViCricleByRadius(1); getActiveGirds.Clear(); foreach (var _attackVi in _attackViArray) { VectorInt2 _resultAttackVi = _playerVi + _attackVi; if (_resultAttackVi < VectorInt2.Zero || _resultAttackVi > (map.Edge - VectorInt2.One)) { continue; } if (map.gridMat [_resultAttackVi.x, _resultAttackVi.y] is BuildGrid) { continue; } getActiveGirds.Add(map.gridMat[_resultAttackVi.x, _resultAttackVi.y]); map.gridMat [_resultAttackVi.x, _resultAttackVi.y].SetGridColor(Color.magenta); } #endregion Ray _ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit _hit = new RaycastHit(); if (Physics.Raycast(_ray, out _hit, 1000f)) { Grid _grid = _hit.collider.GetComponentInParent <Grid> (); if (_grid == null) { break; } if (!getActiveGirds.Contains(_grid)) { break; } if (gridSelect != null) { gridSelect.gameObject.SetActive(true); gridSelect.transform.position = _grid.transform.position; } if (_grid.Owner != null) { if (Input.GetMouseButtonDown(0)) { if (EventSystem.current.IsPointerOverGameObject()) { break; } if (gridSelect != null) { gridSelect.gameObject.SetActive(false); } command = COMMAND.DOING; PlayerFight(player, _grid.Owner); break; } } } } } break; case COMMAND.BUILD: { if (prevCommand != COMMAND.BUILD) { getActiveGirds.Clear(); if (gridSelect != null) { gridSelect.gameObject.SetActive(false); } } if (map != null && player.StandGrid != null) { #region show build range //获得玩家所在grid的坐标 VectorInt2 _playerVi = player.StandGrid.Vi; VectorInt2[] _buildViArray = Util.GetViCricleByRadius(1); getActiveGirds.Clear(); foreach (var _buildVi in _buildViArray) { VectorInt2 _resultBuildVi = _playerVi + _buildVi; if (_resultBuildVi < VectorInt2.Zero || _resultBuildVi > (map.Edge - VectorInt2.One)) { continue; } if (map.gridMat [_resultBuildVi.x, _resultBuildVi.y] is BuildGrid) { continue; } getActiveGirds.Add(map.gridMat[_resultBuildVi.x, _resultBuildVi.y]); map.gridMat [_resultBuildVi.x, _resultBuildVi.y].SetGridColor(Color.green); } #endregion Ray _ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit _hit = new RaycastHit(); if (Physics.Raycast(_ray, out _hit, 1000f)) { Grid _grid = _hit.collider.GetComponentInParent <Grid> (); if (_grid == null) { break; } ; if (!getActiveGirds.Contains(_grid)) { break; } if (gridSelect != null) { gridSelect.gameObject.SetActive(true); gridSelect.transform.position = _grid.transform.position; } if (_grid.Owner == null) { if (Input.GetMouseButtonDown(0)) { if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) { break; } if (gridSelect != null) { gridSelect.gameObject.SetActive(false); } command = COMMAND.DOING; PlayerBuild(player, _grid); break; } } } } } break; case COMMAND.DEFENSE: { } break; case COMMAND.CANCEL: { } break; case COMMAND.DOING: { } break; case COMMAND.END: { PlayerEnd(); } break; case COMMAND.DONE: { command = COMMAND.NONE; } break; default: throw new System.ArgumentOutOfRangeException(); } prevCommand = command; }
// Populate the AStar object and initialize the NPCMovementStepStack private void Awake() { aStar = GetComponent <AStar>(); npcMovementSteps = new Stack <NPCMovementStep>(); }
public void WithTraverserPassed() { AStar <Position> .Solve(_from, _to, Greed, out _, new DefaultTraverser <Position>()); }
public void Baseline() { AStar <Position> .Solve(_from, _to, Greed, out _); }
/* * Update * overrides UnitCommand's Update() * * called once per frame while the command is active * * @returns void */ public override void Update() { if (m_tilePath == null) { //get the start and end of the path Tiles startingTile = map.GetTileAtPos(unit.transform.position); startingTile.unit = null; //get the tile path to follow if (isSafeMove) { m_tilePath = AStar.GetSafeAStarPath(startingTile, endTile, unit, GetArea.GetAreaOfSafeMoveable(startingTile, unit.movementPoints, map, unit)); } else { m_tilePath = AStar.GetAStarPath(startingTile, endTile, unit); } //the path is clear, and the unit can move there if (m_tilePath.Count > 0 && m_tilePath.Count <= unit.movementPoints) { //subtract the path distance from the movement points unit.movementPoints -= m_tilePath.Count; startingTile.unit = null; endTile.unit = unit; } else { //Stop walking Anim if (unit.ArtLink != null) { unit.ArtLink.SetBool("IsWalking", false); } //the path failed startingTile.unit = unit; failedCallback(); return; } } m_timer += Time.deltaTime; //check if there is still a path to follow if (m_tilePath.Count > 0 && m_timer > m_waitTime) { if (m_finishedWaiting == false) { m_finishedWaiting = true; if (unit.ArtLink != null) { unit.ArtLink.SetBool("IsWalking", true); } } //get the next position to go to Tiles nextTile = m_tilePath[0]; //the 3D target of the movement Vector3 target = new Vector3(nextTile.pos.x, 0.15f, nextTile.pos.z); Vector3 relative = target - unit.transform.position; if (relative.magnitude < unit.movementSpeed * Time.deltaTime) { //this is a healing tile, heal the unit if (nextTile.IsHealing(false, unit)) { unit.Heal(GameManagment.stats.tileHealthGained); } //this is a trap tile, it could kill the unit if (nextTile.tileType == eTileType.PLACABLETRAP || nextTile.tileType == eTileType.DAMAGE) { m_timer = 0; m_finishedWaiting = false; if (unit.ArtLink != null) { unit.ArtLink.SetTrigger("TakeDamage"); } unit.Defend(GameManagment.stats.trapTileDamage); //explosion is required if (nextTile.tileType == eTileType.PLACABLETRAP) { //reset the explosion ParticleLibrary.explosionSystem.transform.position = nextTile.transform.position; ParticleLibrary.explosionSystem.time = 0.0f; ParticleLibrary.explosionSystem.Play(); } //Stop walking Anim if (unit.ArtLink != null) { unit.ArtLink.SetBool("IsWalking", false); } } unit.transform.position = target; m_tilePath.RemoveAt(0); if (unit.playerID == 0) { StatisticsTracker.tilesCrossed++; } } else { unit.transform.position += relative.normalized * unit.movementSpeed * Time.deltaTime; } } else if (m_timer > m_waitTime) { if (endTile.tileType == eTileType.PLACABLEDEFENSE || endTile.tileType == eTileType.DEFENSE) { //defensive buff endTile.unit.armour = endTile.unit.baseArmour + 1; } else { //remove the defensive buff endTile.unit.armour = endTile.unit.baseArmour; } successCallback(); //Stop walking Anim if (unit.ArtLink != null) { unit.ArtLink.SetBool("IsWalking", false); } return; } }
public HashSet <Edge> GetCandiateEdges(Vertex src, GeoPoint destPoint, double maxCost, double maxDist) { AStar astar = new AStar(this); return(astar.GetCandiateEdges(src, destPoint, maxCost, maxDist)); }
private void Canvas_Update(ICanvasAnimatedControl sender, CanvasAnimatedUpdateEventArgs args) { upCount++; if (assests_ready && !AStar.IsInitialized() && level != null) { level.InitAStar(); } if ((watch.ElapsedMilliseconds - lastTime) > 1000) { lastTime = watch.ElapsedMilliseconds; Debug.WriteLine("UPS: " + upCount + " , FPS: " + frameCount); upCount = 0; frameCount = 0; if (type == GameType.Client) { if (gotpong && clientState == ClientState.READY) { Debug.WriteLine("Sending ping"); client.Send(new Ping(lastTime)); gotpong = false; } } } //If server of client make special update calls if (type == GameType.Client) { ClientUpdate(); } else if (type == GameType.Host) { ServerUpdate(); } mouse.SetOffset(screen.GetOffset()); //Can be null in case of Client if (level != null) { level.Update(); } if (ui != null) { ui.Update(); } if (Mouse.GetButton() == Mouse.Button.Left) { Vector2 vec2 = Mouse.GetIsoCoordinate(); //Debug.WriteLine("MouseX: " + vec2.X + " MouseY: " + vec2.Y); //Debug.WriteLine("MouseCordX: " + (int)vec2.X / 32 + " MouseCordY: " + (int)vec2.Y / 32); } if (Mouse.GetButton() == Mouse.Button.Right) { test = true; } if (test) { Sound.PlaySound("test.mp3"); test = false; } if (animated_assests_ready && animated_assests_ready2 && animated_assests_ready3 && animated_assests_ready4) { AnimatedSprite.GetUpdateables().ForEach(e => e.Update()); } if (type == GameType.Client) { client.Update(); } if (type == GameType.Host) { server.Update(); } }
public override void map_input_event(Camera camera, InputEvent _event, Vector3 click_position, Vector3 click_normal, int shape_idx, Vector2 chunk, AStar navigation, Node meshMapCtrl, Info info) { }
protected void OnDestroy() { //TODO: change from hard coded AStar.RemoveLayerFromLayout(3); }
private void Route(string s1, string s2, float maxrange, int mode) { Stopwatch sw = new Stopwatch(); if (lastJumprange != maxrange) { G = new Graph(); PrepareNodes(G, out nodes, maxrange, mode); //Console.WriteLine("Prepare nodes time: {0}", sw.Elapsed); lastJumprange = maxrange; } AStar AS = new AStar(G); Node start, stop; start = nodes.FirstOrDefault(x => x.System.SearchName == s1.ToLower()); stop = nodes.FirstOrDefault(x => x.System.SearchName == s2.ToLower()); bool res; if (start == null) { AppendText("Start system: " + s1 + " unknown"); return; } if (stop == null) { AppendText("Destination system: " + s2 + " unknown"); return; } sw = new Stopwatch(); sw.Start(); res = AS.SearchPath(start, stop); sw.Stop(); AppendText("Searching route from " + s1 + " to " + s2 + Environment.NewLine); AppendText("Find route Time: " + sw.Elapsed.TotalSeconds.ToString("0.000s") + Environment.NewLine); AppendText("Total distance: " + SystemData.Distance(s1, s2).ToString("0.00") + Environment.NewLine); AppendText("Max jumprange:" + maxrange + Environment.NewLine); double totdist = 0; int jumps = 0; if (res) { foreach (Arc A in AS.PathByArcs) { double dist = SystemData.Distance(A.StartNode.System.name, A.EndNode.System.name); AppendText(A.EndNode.System.name + " \tDist: " + dist.ToString("0.00") + " ly" + Environment.NewLine); totdist += dist; jumps++; Console.WriteLine(A.ToString()); } // JArray ja = Path2JSON(AS); } else { Console.WriteLine("No result !"); } AppendText("Total distance: " + totdist.ToString("0.00") + Environment.NewLine); AppendText("Jumps: " + jumps + Environment.NewLine); }
public abstract void filter(Point min, AStar astar);
private void ConstructShortestKeyToKeyPaths() { ShortestPathsBetweenKeysIgnoringDoors = new Dictionary <Tuple <GridPoint, GridPoint>, IList <GridPoint> >(); DoorsAlongShortestPathBetweenKeys = new Dictionary <Tuple <GridPoint, GridPoint>, HashSet <string> >(); KeysAlongShortestPathBetweenKeys = new Dictionary <Tuple <GridPoint, GridPoint>, HashSet <string> >(); var keyCells = Keys.Select(k => KeyCells[k]).ToList(); keyCells.AddRange(StartingPositions); for (int i = 0; i < keyCells.Count; i++) { var startKeyCell = keyCells[i]; for (int j = i + 1; j < keyCells.Count; j++) { var targetKeyCell = keyCells[j]; int Heuristic(GridPoint point) { return(GridPoint.GetManhattanDistance(point, targetKeyCell)); } IList <GridPoint> GetNeighbors(GridPoint point) { return(GetPointNeighbors( point: point, keysCollected: new SortedDictionary <string, string>(), specificNeighborToAllow: null, ignoreDoors: true)); } int GetEdgeCost(GridPoint start, GridPoint end) { return(1); } var pathResult = AStar.GetPath <GridPoint>( startPoint: startKeyCell, endPoint: targetKeyCell, Heuristic: Heuristic, GetNeighbors: GetNeighbors, GetEdgeCost: GetEdgeCost); if (pathResult.Path.Count > 0) { var edgeKey12 = new Tuple <GridPoint, GridPoint>(startKeyCell, targetKeyCell); var edgeKey21 = new Tuple <GridPoint, GridPoint>(targetKeyCell, startKeyCell); HashSet <string> keysAlongPath = null; HashSet <string> doorsAlongPath = null; if (!ShortestPathsBetweenKeysIgnoringDoors.ContainsKey(edgeKey12)) { ShortestPathsBetweenKeysIgnoringDoors.Add(edgeKey12, pathResult.Path); keysAlongPath = GetKeysAlongPath(pathResult.Path); doorsAlongPath = GetDoorsAlongPath(pathResult.Path); DoorsAlongShortestPathBetweenKeys.Add(edgeKey12, doorsAlongPath); KeysAlongShortestPathBetweenKeys.Add(edgeKey12, keysAlongPath); } if (!ShortestPathsBetweenKeysIgnoringDoors.ContainsKey(edgeKey21)) { var reversedPath = pathResult.Path.ToList(); reversedPath.Reverse(); ShortestPathsBetweenKeysIgnoringDoors.Add(edgeKey21, reversedPath); keysAlongPath = GetKeysAlongPath(reversedPath); doorsAlongPath = GetDoorsAlongPath(reversedPath); DoorsAlongShortestPathBetweenKeys.Add(edgeKey21, doorsAlongPath); KeysAlongShortestPathBetweenKeys.Add(edgeKey21, keysAlongPath); } } } } }
//移动函数 public void move() { if (!selected_hero.gameObject.GetComponent <HeroManager>().is_moved) { //GetComponent<NetworkView>().RPC("ClearAllObstacle", RPCMode.All); //清楚障碍物 GetComponent <NetworkView>().RPC("findObstacleAndCalculateWaterPower", RPCMode.All);//计算障碍物 //显示可移动范围 Node heroNode = new Node(selected_hero.transform.position); distance = AStar.checkDistance(heroNode, (int)(waterPower / selected_hero.gameObject.GetComponent <HeroManager>().run_power)); for (int i = 0; i < distance.Count; i++) { int row = GridManager.instance.GetRow(GridManager.instance.GetGridIndex(((Node)distance[i]).position)) + 1; int col = GridManager.instance.GetColumn(GridManager.instance.GetGridIndex(((Node)distance[i]).position)) + 1; GameObject theCube = GameObject.Find("Cube " + row + col); theCube.gameObject.GetComponent <MeshRenderer>().enabled = true; } //射线 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Input.GetMouseButtonDown(0) && Physics.Raycast(ray, out hit)) { //目标位置gameobject类型 goal_position = hit.transform.gameObject; //目标位置node类型 Node goalNode = new Node(goal_position.transform.position); //if (hit.transform.tag != "Obstacle") if (!GridManager.instance.IsObstacle(GridManager.instance.CalculateAtNodes(goalNode))) { int moveDistance = FindPathAndReturnDistance(); if (moveDistance * selected_hero.gameObject.GetComponent <HeroManager>().run_power > waterPower) { print("圣水不足"); game_process = Game_process.Choose_operation; } else { selected_hero.GetComponent <NetworkView>().RPC("AnimationPlayState", RPCMode.All, 2); //开始移动 MoveToNode(); print("选择位置成功"); //camMover.Follow(goal_position.transform); selected_hero.gameObject.GetComponent <HeroManager>().is_moved = true; waterPower -= moveDistance * selected_hero.gameObject.GetComponent <HeroManager>().run_power; } //取消移动显示范围 for (int i = 0; i < distance.Count; i++) { int row = GridManager.instance.GetRow(GridManager.instance.GetGridIndex(((Node)distance[i]).position)) + 1; int col = GridManager.instance.GetColumn(GridManager.instance.GetGridIndex(((Node)distance[i]).position)) + 1; GameObject theCube = GameObject.Find("Cube " + row + col); theCube.gameObject.GetComponent <MeshRenderer>().enabled = false; } } //爆炸点 else { print("该单元格为障碍物,无法到达!"); //取消攻击显示范围 for (int i = 0; i < distance.Count; i++) { int row = GridManager.instance.GetRow(GridManager.instance.GetGridIndex(((Node)distance[i]).position)) + 1; int col = GridManager.instance.GetColumn(GridManager.instance.GetGridIndex(((Node)distance[i]).position)) + 1; GameObject theCube = GameObject.Find("Cube " + row + col); theCube.gameObject.GetComponent <MeshRenderer>().enabled = false; } game_process = Game_process.Choose_operation; } } } }
public void LoadMap(string filename) { using (BinaryReader reader = new BinaryReader(new FileStream("Maps/" + filename, FileMode.Open))) { reader.ReadString(); reader.ReadInt32(); if (reader.ReadBoolean()) { using (FileStream str = new FileStream("temp", FileMode.Create)) { byte[] buffer = new byte[reader.ReadInt32()]; reader.Read(buffer, 0, buffer.Length); str.Write(buffer, 0, buffer.Length); } backgroundTexture = new Texture("temp"); backgroundMesh.Texture = backgroundTexture; File.Delete("temp"); } int nmbrOfTilesets = reader.ReadInt32(); for (int i = 0; i < nmbrOfTilesets; i++) { tilesetList.Add(new EnvTileset(reader)); } int nmbrOfTemplates = reader.ReadInt32(); for (int i = 0; i < nmbrOfTemplates; i++) { templateList.Add(new EnvTemplate(reader, this)); } int nmbrOfEvents = reader.ReadInt32(); for (int i = 0; i < nmbrOfEvents; i++) { eventList.Add(new EnvEvent( reader.ReadInt32(), reader.ReadString(), new TKTools.Color(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()) )); } int nmbrOfLayers = reader.ReadInt32(); for (int i = 0; i < nmbrOfLayers; i++) { float depth = 0; if (i == 0) //SOLIDS LAYER { int nmbrOfObjects = reader.ReadInt32(); for (int j = 0; j < nmbrOfObjects; j++) { bool isEvent = reader.ReadBoolean(); if (!isEvent) { solidList.Add(new EnvSolid(reader, this)); } else { int id = reader.ReadInt32(); int argNmbr = reader.ReadInt32(); int[] argList = new int[argNmbr]; for (int a = 0; a < argList.Length; a++) { argList[a] = reader.ReadInt32(); } Polygon p = new Polygon(new Vector2[] { new Vector2(reader.ReadSingle(), reader.ReadSingle()), new Vector2(reader.ReadSingle(), reader.ReadSingle()), new Vector2(reader.ReadSingle(), reader.ReadSingle()), new Vector2(reader.ReadSingle(), reader.ReadSingle()) }); if (id != -1) { map.SceneEvent(eventList.Find((x) => x.ID == id), argList, p); } } } } else { depth = reader.ReadSingle(); EnvLayer layer = new EnvLayer(depth); int nmbrOfObjects = reader.ReadInt32(); for (int j = 0; j < nmbrOfObjects; j++) { EnvObject obj = new EnvObject(reader, depth, this); objectList.Add(obj); layer.AddObject(obj); } layer.CreateCombinedMesh(); layerList.Add(layer); } } Polygon combinedPoly = new Polygon(); List <Polygon> solids = new List <Polygon>(); foreach (EnvSolid solid in solidList) { combinedPoly.AddPoint(solid.polygon); solids.Add(solid.polygon); } RectangleF rect = combinedPoly.Bounds; originOffset = new Vector2(rect.X, rect.Y) + new Vector2(rect.Width / 2, rect.Height / 2); width = rect.Width; height = rect.Height; layerList.Sort(delegate(EnvLayer x, EnvLayer y) { if (x.depth == y.depth) { return(0); } else if (x.depth < y.depth) { return(1); } else { return(-1); } }); AStar.CreateBuffer(solids, 0.5f); } }
public ActionResult setPath(int x, int y) { Console.WriteLine("Set path, X: " + x + " Y: " + y); List <Location> testL = new List <Location>(); int act = 0; foreach (var l in _context.Location) { testL.Add(l); } List <Location> updatedTestL = new List <Location>(); LocationGroup lg = new LocationGroup { locations = testL }; Grid model = new Grid { action = 0, cId = 0, grid = lg }; var a = _context.G; foreach (var ac in a) { if (x == 100 && y == 100) { ac.action = 1; } else if (x == 101 && y == 101) { ac.action = 2; } else if (x == 102 && y == 102) { ac.action = 3; } else if (x == 103 && y == 103) { ac.action = 0; } else if (x == 104 && y == 104) { AStar findPath = new AStar(testL); Console.WriteLine("CHECK B"); updatedTestL = findPath.findPath(); Console.WriteLine("CHECK G"); } _context.SaveChanges(); act = ac.action; } if (x != 104) { Location rip = new Location { XLoc = 0, YLoc = 0, myD = 0 }; foreach (var l in model.grid.locations) { if (l.XLoc == x && l.YLoc == y) { rip = new Location { XLoc = l.XLoc, YLoc = l.YLoc, myD = act }; l.myD = act; _context.SaveChanges(); updatedTestL.Add(rip); } else { updatedTestL.Add(l); } } } model.grid.locations = updatedTestL; return(View("Index", model)); }
static void PlacePowerPoles(Blueprint bp) { Profiler.StartSection("initializePower"); double minx = bp.Entities.Select(e => e.Position.X).Min(); double miny = bp.Entities.Select(e => e.Position.Y).Min(); foreach (var entity in bp.Entities) { entity.Position.Sub(minx - 6, miny - 6); } double maxx = bp.Entities.Select(e => e.Position.X).Max(); double maxy = bp.Entities.Select(e => e.Position.Y).Max(); int width = (int)Math.Ceiling(maxx) + 7; int height = (int)Math.Ceiling(maxy) + 7; Entity[,] occupant = new Entity[width, height]; foreach (var entity in bp.Entities) { int x = (int)entity.Position.X; int y = (int)entity.Position.Y; occupant[x, y] = entity; if (entity.Name.Equals("pumpjack") || entity.Name.Equals("beacon")) { occupant[x - 1, y - 1] = entity; occupant[x - 1, y] = entity; occupant[x - 1, y + 1] = entity; occupant[x, y - 1] = entity; occupant[x, y + 1] = entity; occupant[x + 1, y - 1] = entity; occupant[x + 1, y] = entity; occupant[x + 1, y + 1] = entity; } } Profiler.EndSection(); Profiler.StartSection("power1"); var unpoweredEntityMap = bp.Entities.Where(e => e.Name.Equals("pumpjack") || e.Name.Equals("beacon")).ToDictionary(e => new Coord(e.Position)); var powerPoles = new List <Entity>(); while (unpoweredEntityMap.Count > 0) { const int POWER_POLE_REACH_RADIUS = 4; double highestPowerCount = 0; Position center = new Position(width / 2.0, height / 2.0); double centerBiasDivider = 1 + Math.Sqrt(Math.Pow(center.X, 2) + Math.Pow(center.Y, 2)); Coord bestPosition = new Coord(0, 0); IList <Coord> bestPoweredEntities = new List <Coord>(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (occupant[x, y] != null) { continue; } IList <Coord> poweredEntities = new List <Coord>(); double sum = 0; for (int y2 = -POWER_POLE_REACH_RADIUS; y2 <= POWER_POLE_REACH_RADIUS; y2++) { for (int x2 = -POWER_POLE_REACH_RADIUS; x2 <= POWER_POLE_REACH_RADIUS; x2++) { Coord c = new Coord(x + x2, y + y2); if (unpoweredEntityMap.ContainsKey(c)) { sum++; poweredEntities.Add(c); } } } sum -= Math.Sqrt(Math.Pow(center.X - x, 2) + Math.Pow(center.Y - y, 2)) / centerBiasDivider; if (sum > highestPowerCount) { bestPosition = new Coord(x, y); highestPowerCount = sum; bestPoweredEntities = poweredEntities; } } } if (highestPowerCount <= 0) { break; } Entity powerPole = bp.CreateEntity("medium-electric-pole", bestPosition.X, bestPosition.Y); powerPoles.Add(powerPole); occupant[bestPosition.X, bestPosition.Y] = powerPole; foreach (Coord c in bestPoweredEntities) { unpoweredEntityMap.Remove(c); } } Profiler.EndSection(); if (powerPoles.Count > 1) { Profiler.StartSection("powerMST"); var allPoleIds = powerPoles.Select(p => p.EntityNumber).ToList(); var allEdges = new List <Edge>(); var mstEdges = new HashSet <Edge>(); var mstIds = new HashSet <int>(); for (int i = 0; i < powerPoles.Count; i++) { var p1 = powerPoles[i]; for (int j = 0; j < powerPoles.Count; j++) { if (i == j) { continue; } var p2 = powerPoles[j]; var distance = p1.Position.DistanceTo(p2.Position); allEdges.Add(new Edge() { Start = p1.EntityNumber, End = powerPoles[j].EntityNumber, Distance = distance }); } } allEdges = allEdges.OrderBy(e => e.Distance).ToList(); var edge = allEdges.First(); mstIds.Add(edge.Start); mstIds.Add(edge.End); mstEdges.Add(edge); while (mstIds.Count < allPoleIds.Count) { edge = allEdges.First(e => (!mstIds.Contains(e.Start) && mstIds.Contains(e.End)) || (mstIds.Contains(e.Start) && !mstIds.Contains(e.End))); mstIds.Add(edge.Start); mstIds.Add(edge.End); mstEdges.Add(edge); } Profiler.EndSection(); Profiler.StartSection("powerAStar"); var idToPoleMap = powerPoles.ToDictionary(p => p.EntityNumber); var newPoleSet = new HashSet <Coord>(); AStar astar = new AStar(occupant, 9); foreach (var mstEdge in mstEdges) { if (mstEdge.Distance <= 9) { continue; } Entity pole1 = idToPoleMap[mstEdge.Start]; Entity pole2 = idToPoleMap[mstEdge.End]; Coord start = new Coord(pole1.Position); Coord end = new Coord(pole2.Position); IEnumerable <Coord> e = astar.FindPath(start, end); foreach (Coord c in e) { newPoleSet.Add(c); } } foreach (var pole in powerPoles) { newPoleSet.Remove(new Coord(pole.Position)); } foreach (var pole in newPoleSet) { bp.Entities.Add(new Entity("medium-electric-pole", pole.X, pole.Y)); } } bp.NormalizePositions(); Profiler.EndSection(); }
public void GeneratePath() //from start to finish { path = AStar.GetPath(PortalSpawn, coinSpawn); }
public List <AStarNode> Run(AStarNode startNode, AStarNode endNode) { AStarNode currentNode = startNode; //Debug.Log("************ASTAR RUNNING************"); //Specialfall för första noden eftersom den INTE är något action utan en postCondition, räknar med att den aldrig kommer va mål!!! List <AStarNode> neighbourList = currentNode.GetNeighbours(true); //ger lista med actions som har startNodes preCondition foreach (AStarNode node in neighbourList) { node.SetF(ActionManager.Instance.getAction(node.GetName()).cost + HeuristicCost(node, endNode)); node.SetParent(startNode); openList.Add(node); //Lägg till grannarna för start i openList } //Ta ut nod med lägsta f ur openList while (openList.Count > 0) { int lowInd = 0; for (int i = 0; i < openList.Count; i++) { if (openList[i].GetF() < openList[lowInd].GetF()) { lowInd = i; } } currentNode = openList[lowInd]; openList.Remove(currentNode); closedList.Add(currentNode); //Debug.Log("currentNode är nu: " + currentNode.getName()); //Check if we have reached the target if (ActionManager.Instance.getAction(currentNode.GetName()).preConditions.contains(endNode.GetWorldState())) { return(CreatePath(currentNode, startNode)); } List <List <AStarNode> > lists = new List <List <AStarNode> >(); foreach (KeyValuePair <string, WorldStateValue> pair in ActionManager.Instance.getAction(currentNode.GetName()).preConditions.getProperties()) { //Debug.Log("GDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + pair.Value.propertyValues["amount"]); for (int j = 0; j < (int)pair.Value.propertyValues["amount"]; j++) { //Debug.Log ("IIIIIIIIIIIIII: " + j); AStar astar2 = new AStar(); AStarNode tempNode = new AStarNode(); WorldState tempWorldState = new WorldState(); tempWorldState.setProperty(pair.Key, pair.Value); tempNode.SetWorldState(tempWorldState); List <AStarNode> tempList = new List <AStarNode>(); tempList.AddRange(astar2.Run(tempNode, endNode)); tempList[tempList.Count - 1].SetParent(currentNode); //nyligen tillagd //Debug.Log(".................." + tempList[0].getName() + " får parent " + currentNode.getName()); if (tempList.Count > 0) { lists.Add(tempList); } else { if (!tempWorldState.contains(endNode.GetWorldState())) { return(new List <AStarNode>()); } } } } //Sort by cost to make the plan prioritize actions with small costs lists.Sort((a, b) => ActionManager.Instance.getAction(a[0].GetName()).cost.CompareTo(ActionManager.Instance.getAction(b[0].GetName()).cost)); foreach (List <AStarNode> list in lists) { pathList.AddRange(list); } return(CreatePath(currentNode, startNode)); neighbourList = currentNode.GetNeighbours(false); //Debug.Log ("antal grannar: " + neighbourList.Count); for (int i = 0; i < neighbourList.Count; i++) { //Debug.Log ("***********CurretnNode: " + currentNode.getName() + " neigbour " + neighbourList[i].getName()); AStarNode currentNeighbour = neighbourList[i]; if (closedList.Contains(currentNeighbour)) { //not a valid node continue; } if (!openList.Contains(currentNeighbour)) { //Debug.Log("namnet på grannen: " + currentNeighbour.getName()); //Debug.Log("kontroll om currentneighbour inte finns i openlist: " + !openList.Contains(currentNeighbour)); currentNeighbour.SetH(HeuristicCost(currentNeighbour, endNode)); currentNeighbour.SetG(currentNode.GetG() + currentNeighbour.GetTime()); currentNeighbour.SetF(currentNeighbour.GetG() + currentNeighbour.GetH()); openList.Add(currentNeighbour); } } } //Debug.Log ("det blev fel"); return(new List <AStarNode>()); }
void Start() { LevelData.GetData(); CreateLevel(); AStar.CreateNodes(); }
public static void Chase(EnemyBrain brain, Vector2Int playerPosition) { List <Vector2Int> path = AStar.CalculatePath(brain.position, playerPosition); EnemyMovement.Move(path[0], brain); }
public abstract void min_searcher(AStar astar);
private CubeStar Goto(Cube targetGo) { AStar star = new AStar(manager.map); return(star.FindWay(pos, targetGo)); }
public override IntVec[] viewCastRange(Level level, IntVec start) { radiusSquares = AStar.getPossiblePositionsFrom(level, start, radius, AStar.CharacterTargeting.PASS_THROUGH, false); return(radiusSquares); }
void Start() { var mapchip = Resources.Load <MapchipSet>($"Dungeon/{Dungeon.AssetPath}/MapchipSet"); GridSize = mapchip.GridSize; var postProcessing = Camera.main.GetComponent <PostProcessingBehaviour>(); if (postProcessing != null) { postProcessing.profile = mapchip.PostProcessingProfile; } map = DungeonGen.Gen(stageInfo.seed, Room.AreaSize, Room.RoomNum, Room.RoomMin, Room.RoomMax, Room.DeleteRoadTry, Room.DeleteRoadTry, Room.MergeRoomTry, Room.ObstacleRate, GetAdditionalTile(Dungeon)); var width = map.GetLength(0); var height = map.GetLength(1); Vector2Int?playerGrid = null; var random = new System.Random(stageInfo.seed); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { var info = mapchip.GetChip(map[x, y], random); if (info != null) { var go = Instantiate(info.prefab, Vector3.zero, info.Quaternion, dungeonRoot); go.transform.localRotation = info.Quaternion; go.transform.localPosition = Grid2WorldPosition(new Vector2Int(x, y), GridSize, info.prefab.transform.localPosition); go.name += $"({x},{y})"; } if (map[x, y] == Tile.Start && stageInfo.move == Move.None) { playerGrid = new Vector2Int(x, y); } if ((map[x, y] == Tile.UpStairs && stageInfo.move == Move.Down) || (map[x, y] == Tile.DownStairs && stageInfo.move == Move.Up)) { var pos = new Vector2Int(x, y); if (x - 1 >= 0 && map[x - 1, y] == Tile.All) { pos.x -= 1; } else if (x + 1 < width && map[x + 1, y] == Tile.All) { pos.x += 1; } else if (y - 1 >= 0 && map[y - 1, y] == Tile.All) { pos.y -= 1; } else if (y + 1 < height && map[y + 1, y] == Tile.All) { pos.y += 1; } playerGrid = pos; } } } if (playerGrid.HasValue) { var position = Grid2WorldPosition(playerGrid.Value, GridSize, new Vector3(0, playerPrefab.transform.localPosition.y, 0)); foreach (var uniq in Entity.Instance.StageInfo.pets) { var go = Instantiate(playerPrefab, dungeonRoot); go.transform.localPosition = position; var player = go.GetComponent <Player>(); player.Setup(uniq); players.Add(player); } } cinemachineVirtualCamera.Follow = players.First().transform; Observer.Instance.Subscribe(MapchipEvent.MoveEvent, OnSubscribe); // 経路探索用 A* 生成 aStar = new AStar(map); }
public List <TileScript> GetValidMoveableTilesWithinRange(int range, TileScript tileFrom) { // iterate through every tile, and add those within range to the temp list TileScript[] allTiles = FindObjectsOfType <TileScript>(); List <TileScript> allTilesWithinXPosRange = new List <TileScript>(); List <TileScript> allTilesWithinRange = new List <TileScript>(); List <TileScript> allTilesWithinMobilityRange = new List <TileScript>(); // first, filter in all tiles with an X grid position within movement range foreach (TileScript tile in allTiles) { int myXPos = tile.GridPosition.X; if ( (myXPos >= tileFrom.GridPosition.X && (myXPos <= tileFrom.GridPosition.X + range)) || (myXPos <= tileFrom.GridPosition.X && (myXPos >= tileFrom.GridPosition.X - range)) ) { //only add tiles to the list if they are walkable and unoccupied if (tile.CanBeMovedThrough() && tile.CanBeOccupied()) { allTilesWithinXPosRange.Add(tile); } /* * if (tile.isEmpty == true && tile.isWalkable == true) * { * allTilesWithinXPosRange.Add(tile); * } */ } } // second, filter out all tiles outside of Y range, then add the remainding tiles to the final list. foreach (TileScript Xtile in allTilesWithinXPosRange) { int myYPos = Xtile.GridPosition.Y; if ( (myYPos >= tileFrom.GridPosition.Y && myYPos <= tileFrom.GridPosition.Y + range) || (myYPos <= tileFrom.GridPosition.Y && (myYPos >= tileFrom.GridPosition.Y - range)) ) { allTilesWithinRange.Add(Xtile); } } // third, remove the 'fromTile' from the list allTilesWithinRange.Remove(tileFrom); // fourth, draw a path to each tile in the list, filtering the ones within mobility range foreach (TileScript tile in allTilesWithinRange) { Stack <Node> path = AStar.GetPath(tileFrom.GridPosition, tile.GridPosition); if (path.Count <= range) { allTilesWithinMobilityRange.Add(tile); } } //Debug.Log("Tiles within range: " + allTilesWithinRange.Count); return(allTilesWithinMobilityRange); }