// Walk a player or monster token to a space private void WalkActor(Actor actor, int xTo, int zTo) { // Find a path to the desired square, by getting a queue of sqaures to hop over LinkedList <TokenWalker.Hop> hopsQueue = Pathfind.FindPath(actor.x, actor.z, xTo, zTo); if (hopsQueue != null) { if (hopsQueue.Count > currentTurnStats.MovementLeft) { PopupTextController.PopupText("Not Enough Movement", spaces[xTo, zTo].gameSpace.transform); } else { // change the token's stored properties to its final position spaces[actor.x, actor.z].isBlocked = false; actor.x = xTo; actor.z = zTo; spaces[xTo, zTo].isBlocked = true; SetState(STATES.ANIMATING_ACTION); // Use the script attached to the token to walk the path actor.tokenRef.GetComponent <TokenWalker>().WalkPath(hopsQueue); } } else { PopupTextController.PopupText("Pathfinding failed", spaces[xTo, zTo].gameSpace.transform); } }
void Awake() { _tilemapManager = gfm.tilemapManager; _pathfind = new Pathfind { tilemapManager = _tilemapManager }; _agent = GetComponent <Agent>(); }
void Awake() { pathfind = GetComponent <Pathfind>(); Assert.IsNotNull(graph, "GraphLoader():: graph is null"); Assert.IsNotNull(pathfind, "GraphLoader():: pathfind is null"); Assert.IsNotNull(edgePrefab, "GraphLoader():: edgePrefab is null"); nodes = graph.nodes; }
void Awake() { _animator = GetComponent <Animator>(); _hitbox = transform.GetChild(0).GetComponent <BoxCollider2D>(); _rb = GetComponent <Rigidbody2D>(); _sr = GetComponent <SpriteRenderer>(); _ps = transform.GetChild(1).GetComponent <ParticleSystem>(); _patrolScript = GetComponent <Patrol>(); _pathfindScript = GetComponent <Pathfind>(); _player = GameObject.Find("Player"); _currentHealth = _maxHealth; _healthBar.SetHealth(_currentHealth, _maxHealth); }
protected void Awake() { pathfind = new Pathfind { tilemapManager = tilemapManager }; gridElement = GetComponent <GridElement>(); status = AgentStatus.Normal; if (gridElement.solid && pushable) { Debug.LogWarning("Agent is pushable but gridElement is set to solid. overriding gridElement solid to false"); gridElement.solid = false; } }
// Cell is a board edge if it has less than 6 neighbours public bool IsWin() { // Don't assess cells more than once HashSet <IGraphNode> visitedCells = new HashSet <IGraphNode>(); // Get all cells connected by a pipe and not already visited IEnumerable <Pipe> pipes = _pipeManager.Pipes .Where(p => !visitedCells.Contains(p)); // Iterate all cells connected with pipes foreach (Pipe pipe in pipes) { // Don't revisit a pipe visitedCells.Add(pipe); // Assemble a list of all the edges this pipe networks touches List <BoxEdge> edges = new List <BoxEdge>(); // Iterate all connected pipes foreach (PathStep step in Pathfind.Enumerate(pipe, -1)) { Pipe neighbourPipe = step.Node as Pipe; foreach (HexCell pipeCell in neighbourPipe.Cells) { // Add all the edges it touches to list of edges if (pipeCell.IsEdgeCell) { edges.AddRange(pipeCell.GetEdges()); } } } // Check if there are any opposite edges for (int i = 0; i < edges.Count; i++) { for (int j = i + 1; j < edges.Count; j++) { // If pipe network visits opposite edges then its a win!s if (edges[i].IsOpposite(edges[j])) { return(true); } } } } return(false); }
/// <summary> /// Peds created here are deleted when the Client leaves. They are found in <see cref="RAGE.Elements.Entities.Peds"/> /// </summary> /// <param name="pedHash"></param> /// <param name="pos"></param> /// <param name="heading"></param> /// <returns></returns> public static RAGE.Elements.Ped CreatePed(uint pedHash, Vector3 pos, float heading = 180f) { //Create safe ground for ped Vector3 posSafe = new Vector3(); while (!Pathfind.GetSafeCoordForPed(pos.X, pos.Y, pos.Z, true, posSafe, 16)) { } //Just set the Z pos otherwise get put on nearest pavement, or middle of road. pos.Z = posSafe.Z + 0.25f; Entities.Peds.All.Add(new RAGE.Elements.Ped(pedHash, pos, heading)); return(Entities.Peds.All.Last()); }
public override TaskStatus OnUpdate() { finder = myAgent.Value.GetPathfinder(); if (myAgent.Value.atDestination) { return(TaskStatus.Success); } if (pathFailed) { return(TaskStatus.Failure); } StartCoroutine(MoveTowardsDestination()); return(TaskStatus.Running); }
public static void test_dir_to() { Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(0, 1)), Direction.N); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(1, 0)), Direction.E); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(1, 1)), Direction.NE); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(0, -1)), Direction.S); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(-1, 0)), Direction.W); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(-1, -1)), Direction.SW); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(-1, 1)), Direction.NW); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(1, -1)), Direction.SE); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(0, 0)), Direction.NONE); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(1, 10)), Direction.N); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(8, 10)), Direction.NE); Equal(Pathfind.direction_to(new Loc(0, 0), new Loc(12, 4)), Direction.E); Ok(); }
public override TaskStatus OnUpdate() { agent = myAgent.Value; finder = agent.SetDestination(destination.Value); if (agent.atDestination) { return(TaskStatus.Success); } if (pathFailed) { return(TaskStatus.Failure); } StartCoroutine(MoveTowardsDestination()); return(TaskStatus.Running); }
public MainGame() { bQuit = false; //Ui alert = new Alert(); //GFX TILESET = new Tileset(); //Map mPathF = new Pathfind(); visibleMap = new List <Tile>(); //Items activeItems = new List <Item>(); activeFoods = new List <Item>(); activeDiamonds = new List <Item>(); //Actors activeEnemies = new List <Character>(); //Spawners enemySpawner = new EnemySpawner(); itemSpawner = new ItemSpawner(); //Enemies pool, placeholder for test. enemyPool = new int[] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 }; enemyPool2 = new int[] { 110, 111, 112, 113, 114, 115, 116, 117, 118, 119 }; enemyPool3 = new int[] { 120, 121, 122, 123, 124, 125 }; //Items pool, placeholder for test. itemPool1 = new int[] { 100, 101, 102, 103, 150, 151, 152, 153, 154, 200, 201, 202, 251 }; //HolderPool { 100, 101, 102, 103, 150, 151, 152, 153, 154, 200, 201, 202, 251 }; Console.CursorVisible = true; Console.Clear(); playerName = alert.Question("Who are you?"); Console.CursorVisible = false; GameStart(); }
public void DrawPath(List <Cell> path) { tilemap.ClearAllTiles(); DataGrid <Pathfind.CellData> dijkstra = Pathfind.Dijkstra(startCell, collisionTilemap); Cell min = new Cell(int.MaxValue, int.MaxValue), max = new Cell(-int.MaxValue, -int.MaxValue); foreach (Cell cell in path) { if (min.x > cell.x) { min.x = cell.x; } if (min.y > cell.y) { min.y = cell.y; } if (max.x < cell.x) { max.x = cell.x; } if (max.y < cell.y) { max.y = cell.y; } } DataGrid <int> grid = new DataGrid <int>(min, max); foreach (Cell cell in path) { grid[cell + Cell.left] += 1 << 0; grid[cell + Cell.up] += 1 << 1; grid[cell + Cell.right] += 1 << 2; grid[cell + Cell.down] += 1 << 3; } foreach (Cell cell in path) { tilemap.SetTile(new Vector3Int(cell.x, cell.y, 0), Tiles[grid[cell]]); } }
void Die() { _healthBar.Destroy(); Patrol patrol = GetComponent <Patrol>(); if (patrol != null) { patrol.Stop(); } Pathfind pathfind = GetComponent <Pathfind>(); if (pathfind != null) { pathfind.Stop(); } _hitbox.enabled = false; _rb.bodyType = RigidbodyType2D.Kinematic; transform.rotation = Quaternion.Euler(0, 0, 0); _animator.SetBool("isDead", true); Destroy(gameObject, _deathAnimationDuration); }
void Update() { Cell selectedCell = GridManager.GetMouseCell(); if (EventSystem.current == null || !EventSystem.current.IsPointerOverGameObject()) { if (Input.GetButtonDown("Fire1")) { if (GridManager.GetEntityAt <Character>(selectedCell) != null) { startCell = GridManager.GetMouseCell(); if (startCursorInstance != null) { startCursorInstance.transform.position = GridManager.GetCellPos(startCell); } previewPathDrawer.ClearPath(); } else if (GridManager.GetEntityAt <Character>(startCell) != null) { List <Cell> path = Pathfind.GetPathFromDijkstra(Pathfind.Dijkstra(startCell, collisionTilemap), startCell, targetCell); SetPathForCell(startCell, path); } } if (GridManager.GetEntityAt <Character>(startCell) != null && targetCell != GridManager.GetMouseCell()) { targetCell = GridManager.GetMouseCell(); if (endCursorInstance != null) { endCursorInstance.transform.position = GridManager.GetCellPos(targetCell); } List <Cell> path = Pathfind.GetPathFromDijkstra(Pathfind.Dijkstra(startCell, collisionTilemap), startCell, targetCell); previewPathDrawer.DrawPath(path); } } }
// Use this for initialization void Start() { Pathfind.BFS(tiles, tiles[1][1], tiles[(int)size.x - 1][(int)size.y - 1], null); Pathfind.ShowMoves(tiles, tiles[9][9], 3, 1); }
void Awake() { Instance = this; Pathfind.bf = this; Pathfind.Init(); }
protected List <int> get_targets() { Game_Unit unit = get_unit(); List <int> temp_targets = new List <int>(); switch (Mode) { // Looking for people to rescue case 0: List <int> rescue_targets = unit.allies_in_range(1); foreach (int id in rescue_targets) { if (unit.can_rescue(Global.game_map.units[id])) { temp_targets.Add(id); } } break; // Looking for drop locations case 1: foreach (Vector2 loc in unit.drop_locs()) { temp_targets.Add((int)(loc.X + loc.Y * Global.game_map.width)); } /*foreach (Vector2 loc in new Vector2[] { new Vector2(0, 1), new Vector2(0, -1), new Vector2(1, 0), new Vector2(-1, 0) }) //Debug * if (!Global.game_map.is_off_map(loc + unit.loc)) * if (!Global.game_map.is_blocked(loc + unit.loc, unit.rescuing)) * if (Pathfinding.passable(Global.game_map.units[unit.rescuing], loc + unit.loc)) * temp_targets.Add((int)((loc + unit.loc).X + (loc + unit.loc).Y * Global.game_map.width));*/ break; // Looking for people to take case 2: List <int> take_targets = unit.allies_in_range(1); foreach (int id in take_targets) { if (Global.game_map.units[id].different_team(unit)) { continue; } if (!Global.game_map.units[id].is_rescuing) { continue; } if (unit.can_rescue(Global.game_map.units[Global.game_map.units[id].rescuing])) { temp_targets.Add(id); } } break; // Looking for people to give to case 3: List <int> give_targets = unit.allies_in_range(1); foreach (int id in give_targets) { if (Global.game_map.units[id].different_team(unit)) { continue; } if (Global.game_map.units[id].is_rescuing) { continue; } if (!Global.game_map.units[id].is_rescue_blocked() && Global.game_map.units[id].can_rescue(Global.game_map.units[unit.rescuing])) { temp_targets.Add(id); } } break; // Skills: Savior // Looking for people to cover case 4: List <int> cover_targets = unit.allies_in_range(1); foreach (int id in cover_targets) { if (unit.can_rescue(Global.game_map.units[id])) { if (Pathfind.passable(unit, Global.game_map.units[id].loc)) { temp_targets.Add(id); } } } break; // Looking for people to take refuge under case 5: List <int> refuge_targets = unit.allies_in_range(1); foreach (int id in refuge_targets) { Game_Unit target = Global.game_map.units[id]; if (target.has_refuge() && target.can_rescue(unit)) { temp_targets.Add(id); } } break; } return(temp_targets); }
private void AddSkillCommands(ref List <string> commands, Game_Unit unit) { // Actions: // 100 = Shelter // 101 = Dash // 102 = Swoop // 103 = Trample // 104 = Sacrifice // 105 = Refuge // 120 = Old Swoop //Debug if (CantoAllowsNormalActions(Canto)) { // Skills: Savior if (commands.Contains("Rescue") && unit.has_cover() && !unit.is_rescue_blocked()) { List <int> allyRange = unit.allies_in_range(1); bool canRescue = false; foreach (int id in allyRange) { if (unit.can_rescue(Global.game_map.units[id])) { if (Pathfind.passable(unit, Global.game_map.units[id].loc)) { canRescue = true; break; } } } if (canRescue) { int index = commands.IndexOf("Rescue"); commands.Insert(index + 1, "Shelter"); AddSkillIndex(index, SkillMenuIds.Shelter); } } { List <int> allyRange = unit.allies_in_range(1); bool canTakeRefuge = false; foreach (int id in allyRange) { Game_Unit target = Global.game_map.units[id]; if (target.has_refuge() && target.can_rescue(unit) && !unit.is_rescue_blocked()) { canTakeRefuge = true; break; } } if (canTakeRefuge) { // Place before status and wait, at least int index = Math.Min( commands.IndexOf("Status"), commands.IndexOf("Wait")); // Try placing before Item int itemIndex = commands.IndexOf("Item"); if (itemIndex >= 0) { index = itemIndex; } // Try placing after rescue int rescueIndex = commands.IndexOf("Rescue"); if (rescueIndex >= 0) { index = rescueIndex + 1; } // Try placing after shelter int shelterIndex = commands.IndexOf("Shelter"); if (shelterIndex >= 0) { index = shelterIndex + 1; } commands.Insert(index + 0, "Refuge"); AddSkillIndex(index - 1, SkillMenuIds.Refuge); } } // Skills: Dash if (unit.actor.has_skill("DASH")) { // Can move and not in starting location/has done something if (unit.base_mov > 0 && (unit.turn_start_loc != unit.loc || Canto != Canto_Records.None)) { int index = Math.Min( commands.IndexOf("Status"), commands.IndexOf("Wait")); commands.Insert(index + 0, "Dash"); AddSkillIndex(index - 1, SkillMenuIds.Dash); } } // Skills: Swoop if (unit.actor.has_skill("SWOOP")) { List <int>[] ary = unit.enemies_in_swoop_range(); List <int> enemyRange = ary[0]; if (enemyRange.Count > 0) { Global.game_temp.temp_skill_ranges["SWOOP"] = unit.swoop_range(); Global.game_map.range_start_timer = 0; int index = commands.IndexOf("Attack"); commands.Insert(index + 1, "Swoop"); AddSkillIndex(index, SkillMenuIds.Swoop); } } // Skills: Trample if (unit.actor.has_skill("TRAMPLE")) { List <int>[] ary = unit.enemies_in_trample_range(); List <int> enemyRange = ary[0]; if (enemyRange.Count > 0) { Global.game_temp.temp_skill_ranges["TRAMPLE"] = unit.trample_range(); Global.game_temp.temp_skill_move_ranges["TRAMPLE"] = unit.trample_move_range(); Global.game_map.range_start_timer = 0; int index = commands.IndexOf("Attack"); commands.Insert(index + 1, "Trample"); AddSkillIndex(index, SkillMenuIds.Trample); } } // Skills: Sacrifice if (unit.actor.has_skill("SACRIFICE")) { if (unit.actor.hp > 1) { List <int> allyRange = unit.allies_in_range(1); bool canHeal = false; foreach (int id in allyRange) { if (!Global.game_map.units[id].actor.is_full_hp()) { canHeal = true; break; } } if (canHeal) { int index = commands.IndexOf("Attack"); commands.Insert(index + 1, "Sacrifice"); AddSkillIndex(index, SkillMenuIds.Sacrifice); } } } // Skills: Old Swoop //@Debug if (unit.actor.has_skill("OLDSWOOP")) { List <int>[] ary = unit.enemies_in_old_swoop_range(); List <int> enemyRange = ary[0]; if (enemyRange.Count > 0) { Global.game_temp.temp_skill_ranges["OLDSWOOP"] = unit.old_swoop_range(); Global.game_map.range_start_timer = 0; int index = commands.IndexOf("Attack"); commands.Insert(index + 1, "OldSwoop"); AddSkillIndex(index, SkillMenuIds.OldSwoop); } } // Skills: Masteries for (int i = 0; i < Game_Unit.MASTERIES.Count; i++) { if (unit.actor.has_skill(Game_Unit.MASTERIES[i]) && unit.is_mastery_ready(Game_Unit.MASTERIES[i])) { string skill = Game_Unit.MASTERIES[i]; List <int>[] rangeAry = unit.enemies_in_range(skill); if (rangeAry[1].Count > 0) { List <int> itemIndices = unit.weapon_indices(rangeAry[1]); Global.game_temp.temp_skill_ranges[skill] = unit.get_weapon_range(itemIndices, new HashSet <Vector2> { unit.loc }, skill); //Global.game_temp.temp_skill_ranges[skill] = Global.game_map.get_unit_range(new List<Vector2> { unit.loc }, // unit.min_range_absolute(skill), unit.max_range_absolute(skill), Game_Unit.mastery_blocked_through_walls(skill)); Global.game_map.range_start_timer = 0; int index = commands.IndexOf("Attack"); commands.Insert(index + 1, Global.skill_from_abstract(skill).Name); IndexRedirect.Insert(index + 1, BASE_MASTERY_MENU_ID + i); } } } } }
protected virtual void FindNextMovePoint() { strategyPoint = Pathfind.GetNextWaypoint(force, GetStandPlaceName(), transform.position); // Debug.Log(strategyPoint.name); }
/// <summary> /// Generates a path from the starting position to (finalX,finalY) /// </summary> /// <param name="finalX">X position of the destinaton.</param> /// <param name="finalY">Y position of the destinaton.</param> /// <param name="forcedir">Prevents zigzagging</param> /// <param name="maxRec">maximum recursions. If this is passed, the character will say the path is "too confusing" and quit. Setting to a negative number disables this.</param> public string GenNext(float finalX, float finalY, int forcedir = 0, int maxRec = 5) { if(maxRec == 0) { return "That path is too confusing\n"; } Pathfind p = (Pathfind)ScriptableObject.CreateInstance<Pathfind>(); Vector3 vStart = new Vector3(xEnd, yEnd); Vector3 vEnd = new Vector3 (finalX, finalY); //represents the direction from the end of the current path to the start of the next. vDir will move clockwise and vDirb will move counterclockwise Vector3 vDir = vStart - vEnd; vDir.Normalize (); vDir = vDir * (-1); Vector3 vDirb = new Vector3 (vDir.x, vDir.y); //Sets the maximum raycast distance, or if no obstance is detected immediately creates the final path float maxDist = Vector3.Distance(vStart,vEnd); RaycastHit rHit; Physics.Raycast (vStart, vDir, out rHit, maxDist); if(rHit.collider == null) { p.xEnd = finalX; p.yEnd = finalY; next = p; return "Moving to position"; } //Rotates vDir and vDirb in opposite directions until one or the other finds a clear path //forcedir will allow the pathfind to ignore one direction or another while((forcedir == 2 || Physics.Raycast(vStart,vDir,maxDist)) && (forcedir == 1 || Physics.Raycast(vStart,vDirb,maxDist))) { vDir = Vector3.Cross (vDir, (Vector3.forward * Mathf.PI * 0.1F)); vDirb = Vector3.Cross (vDirb, (Vector3.forward * Mathf.PI * -0.1F)); if(vDir.x == vDirb.x && vDir.y == vDirb.y) { return "I got lost\n"; } } float xTest = xEnd; float yTest = yEnd; float distTest = Mathf.Pow(xEnd,2) + Mathf.Pow(yEnd,2); //the sqrt doesn't matter, since all I care about is if distance is decreasing or increasing) //moves a test point in the direction selected until it starts getting further away from the final destination if(Physics.Raycast(vStart,vDirb) && !(forcedir == 2)) { forcedir = 1; while(distTest >= (Mathf.Pow(xTest,2) + Mathf.Pow(yTest,2))) { distTest = Mathf.Pow(xTest,2) + Mathf.Pow(yTest,2); xTest += vDir.x; yTest += vDir.y; } } else { forcedir = 2; while(distTest >= ((Mathf.Pow(xTest,2) + Mathf.Pow(yTest,2)) - 10)) { distTest = Mathf.Pow(xTest,2) + Mathf.Pow(yTest,2); xTest += vDirb.x; yTest += vDirb.y; } } p.xEnd = xTest; p.yEnd = yTest; next = p; MonoBehaviour.print ("path to (+ " + xTest + "," + yTest + ")"); //If the final destination isn't found, keep going until it is if(((Mathf.Pow(p.xEnd - finalX,2)) > 1) || ((Mathf.Pow(p.yEnd - finalY,2)) > 1)) { return next.GenNext(finalX, finalY, forcedir, maxRec - 1); } return "Moving to position"; }
// Resolve an attack action // Recevied from any arbitrary GameObject with the OnClick-Message script attached public void MessageClickedToken(GameObject attackee) { SetState(STATES.ANIMATING_ACTION); if (currentTurnStats.HasAttackHappened) { PopupTextController.PopupText("Already attacked", attackee.transform); } else { GameObject attacker = actors[currentActorTurn].tokenRef; if (attackee == attacker) { PopupTextController.PopupText("Can't attack self", attackee.transform); } else { Actor victim = actors.Find(actor => { return(actor.tokenRef == attackee); }); if (victim == null) { PopupTextController.PopupText("ERROR FINDING ACTOR", attackee.transform); } else { if (!victim.IsAlive) { PopupTextController.PopupText("Creature is already dead", attackee.transform); } else { // Check if attack is possible, using A* pathfinding to find range in num squares, manhattan distance if (Pathfind.FindDistance(actors[currentActorTurn].x, actors[currentActorTurn].z, victim.x, victim.z) > actors[currentActorTurn].AttackRange) { PopupTextController.PopupText("Out of range", attackee.transform); } else { // Roll to hit int attackResult = RollDice(1, 20, actors[currentActorTurn].AttackMod); if (attackResult >= victim.AC) { PopupTextController.PopupText("Hit: " + attackResult + " vs. " + victim.AC, attacker.transform); // Animate attack attacker.GetComponent <TokenAttacker>().AttackTowards(attackee.transform); int damageResult = RollDice(actors[currentActorTurn].DamageDieNum, actors[currentActorTurn].DamageDieMagnitude, actors[currentActorTurn].DamageMod); victim.HP -= damageResult; delayedMessage = damageResult + " damage"; delayedActor = victim; Invoke("DelayDamagePopup", 0.5f); return; } else { PopupTextController.PopupText("Miss: " + attackResult + " vs. " + victim.AC, attackee.transform); } // Finalise attack currentTurnStats.HasAttackHappened = true; } } } } } SetState(STATES.AWAITING_INPUT); CheckForTurnCompleted(); }