protected void Awake() { _steeringController = GetComponent<SteeringController>(); _return = GetComponent<FS_Marge_ReturnHomer>(); _pathFinder = GameObject.Find("PathFinder").GetComponent<PathFinder>(); }
// Use this for initialization void Awake() { enemyUnits = new List<Unit>(); allyUnits = new List<Unit>(); parent = gameObject; enemyUnitObjects = GameObject.Find("Enemy Units"); allyUnitObjects = GameObject.Find("Ally Units"); enemyUnitObjects.transform.parent = parent.transform; allyUnitObjects.transform.parent = parent.transform; pathManager = new GraphManager(parent); pathFinder = pathManager.getGraph(); //TODO: Integrate PCG here //OR generate more spawns than needed and randomly select from generated spawn points. Vector2 topright = pathFinder.getTopRightBound(); Vector2 botleft = pathFinder.getBottomLeftBound(); Vector2 mid = topright - botleft; mid /= 3; KeyValuePair<List<Node>, List<Node>> spawnPoints = pathFinder.getSpawnPoints(topright - mid, botleft + mid, 5); for (int i = 0; i < spawnPoints.Key.Count; i++) { Node spawnEnemy = spawnPoints.Key[i]; Node spawnAlly = spawnPoints.Value[i]; addLongArmUnit(enemyUnits, enemyUnitObjects, "Enemy LongArm", spawnEnemy, true); addLongArmUnit(allyUnits, allyUnitObjects, "Ally LongArm", spawnAlly, false); } enemyUnits.Reverse(); allyUnits.Reverse(); turnManager = new TurnManager(pathFinder, allyUnits, enemyUnits); }
public AzioneMovimento(Quantum quantum, Casella casellaPartenza, bool puòAttaccare = true) { this.casellaPartenza = casellaPartenza; naveMossa = casellaPartenza.Occupante; this.quantum = quantum; this.puòAttaccare = puòAttaccare; // Faccio partire il pathfinder pathFinder = new PathFinder(); pathFinder.Start(this.casellaPartenza, naveMossa.MuoveInDiagonale); // Illumino le caselle raggiungibili int[] caselleRaggiungibili = Tile.Tiles(t => { Casella casella = t as Casella; int d = pathFinder.DistanzaCasella(t); return (d <= naveMossa.Pwr && d > 0 && (puòAttaccare || (casella != null && casella.Occupante == null) )); } ).Select(t => t.ID).ToArray(); quantum.getGUI().Tabellone.ResetSelezioneMouse(); quantum.getGUI().Tabellone.IlluminaCaselle(caselleRaggiungibili); }
public override void Start() { Params.Load("default.txt"); targetPos = new Vector3(20, 0, 250); startPos = new Vector3(10, 0, -20); leader = CreateBoid(startPos, boidPrefab); CreateObstacle(new Vector3(15, 0, 10), 10); CreateObstacle(new Vector3(5, 0, 50), 12); CreateObstacle(new Vector3(15, 0, 70), 5); pathFinder = new PathFinder(); Path path = pathFinder.FindPath(startPos, targetPos); path.Looped = false; path.draw = true; leader.GetComponent<SteeringBehaviours>().path = path; leader.GetComponent<SteeringBehaviours>().turnOn(SteeringBehaviours.behaviour_type.follow_path); CreateCamFollower(leader, new Vector3(0, 5, -10)); GroundEnabled(false); }
/// <summary> /// Gets the best possible path (approximate solution) using a A* alogrithm. /// </summary> /// <param name="start"></param> /// <param name="target"></param> /// <param name="criteria"></param> /// <param name="minSecurityLevel">The minimum, inclusive, security level.</param> /// <param name="maxSecurityLevel">The maximum, inclusive, security level.</param> /// <returns></returns> private static PathFinder FindBestPathCore(SolarSystem start, SolarSystem target, PathSearchCriteria criteria, float minSecurityLevel, float maxSecurityLevel) { Dictionary<SolarSystem, int> bestDepths = new Dictionary<SolarSystem, int>(); SortedList<int, PathFinder> paths = new SortedList<int, PathFinder>(); PathFinder root = new PathFinder(start); bestDepths.Add(start, -1); paths.Add(0, root); while (true) { if (paths.Count == 0) return null; PathFinder best; int depth; // Pick the best candidate path, but ensures it matches the best depth found so far while (true) { // Picks the best one, returns if we found our target best = paths.Values[0]; if (best.m_system == target) return best; // Removes it from the list paths.RemoveAt(0); int bestDepth; depth = best.Depth; bestDepths.TryGetValue(best.m_system, out bestDepth); if (bestDepth == depth || best.m_system == start) break; } // Gets the subpaths for the best path so far depth++; foreach (PathFinder child in best.GetChildren(depth, bestDepths)) { // Gets the heuristic key based on path search criteria int criteriaValue = criteria == PathSearchCriteria.ShortestDistance ? child.m_system.GetSquareDistanceWith(target) : 1; int key = criteriaValue * depth * depth; if (child.m_system.SecurityLevel < minSecurityLevel || child.m_system.SecurityLevel > maxSecurityLevel) key *= 100; while (paths.ContainsKey(key)) { key++; } // Stores it in the sorted list paths.Add(key, child); } } }
public static PathFinder Instance() { if (_instance == null) { _instance = new PathFinder(); } return _instance; }
/// <summary> /// Outputs three examples of path finding to the Console. /// </summary> /// <remarks>The examples have copied from the unit tests!</remarks> public List<Point> Find(int[,] iMap, Point S, Point F) { // Start with a clear map (don't add any obstacles) InitializeMap(iMap, S, F); PathFinder pathFinder = new PathFinder(sp); List<Point> path = pathFinder.FindPath(); return path; }
public BruteForceRegionFinder(Level level) : base(level) { this.pathFinder = PathFinder.CreateInstance(level); // Initialize map of coordinates already tried. tried = new Array2D<bool>(level.Height, level.Width); }
void Awake() { mSceneCamera = GameObject.Find("Main Camera").GetComponent<Camera>(); mDestination = cachedTransform.position; gridModel = GameObject.Find("GridArea").GetComponent<GridModel>(); pathFinder = new PathFinder(gridModel); }
public static PathFinder Instance() { if (_instance == null) { Debug.Log("PathFinder: Instance is NULL. Run around in circles and panic."); _instance = new PathFinder(); } return _instance; }
public void Initialize(Level level, PathFinder pathFinder) { Level = level; PathFinder = pathFinder; SokobanRow = level.SokobanRow; SokobanColumn = level.SokobanColumn; level.RemoveSokoban(); HashKey = level.GetOccupantsHashKey(); }
public override bool CanElveDoJob(ElveBehavior elve) { PathFinder<VoxelNode> pather = new PathFinder<VoxelNode>(VoxelGraph.Instance, (n1, n2) => new VoxelEdge(n1, n2, PathingConstants.MovementTypes.Walk)); pather.Start = new VoxelNode((Vector2)elve.MyTransform.position); pather.End = new VoxelNode(PlantPos); return pather.FindPath(); }
private void btnStart_Click(object sender, EventArgs e) { if (pathFinder == null) { pathFinder = new PathFinder(new Cell(0,0), new Cell(blocks.Length, blocks[0].Length), blocks); } timer1.Enabled = !timer1.Enabled; btnStart.Text = timer1.Enabled ? "Stop" : "Start"; }
public void StartAIMovement( ) { cachedTransform = this.gameObject.transform.position; //skeletonAnimation = this.GetComponentInChildren< SkeletonAnimation >( ); aiPathFinder = this.GetComponent< PathFinder >( ); StartCoroutine( MoveAI( ) ); startTime = Time.time; journeyLength = Vector3.Distance( this.transform.position, aiPathFinder.listOfTargets[0].transform.position ); }
// Update is called once per frame void Update () { //checkInput(); //Handle User input if (pathFinder == null) pathFinder = GameObject.FindGameObjectWithTag("LevelManager").GetComponent<LevelManager>().getPathFinder(); else { follow(); seek(); //Seek target destination based on path selected } }
protected SubsetSolver(Level level, bool incremental) { this.level = level; pathFinder = PathFinder.CreateInstance(level,false, incremental); regionFinder = RegionFinder.CreateInstance(level); sokobanMap = new Array2D<bool>(level.Height, level.Width); cancelInfo = new CancelInfo(); }
// Update is called once per frame void Update () { goals.ForEach(g=>g.updatePrerequisites(this)); List<Goal> pendingGoals = goals.SkipWhile(g=>g.nextGoal(this) == null).ToList(); if (pendingGoals.Any()) { Goal nextGoal = pendingGoals.First().nextGoal(this); Debug.Log(nextGoal); switch(nextGoal.GetType().ToString()) { case "GoalLocation": GoalLocation goalLocation = nextGoal as GoalLocation; if (goalIndicator != null) { goalIndicator.position = grid.positionForCoord(goalLocation.pos); } if (Time.time > pathLastUpdated + .5f) { PathFinder pathFinder = new PathFinder(manager,grid.navigable(),grid.coordForPosition(transform.position),goalLocation.pos); path = pathFinder.shortest(); pathLastUpdated = Time.time; } if (path != null) { Vector3 direction = (grid.positionForCoord(path.First()) - transform.position).normalized; Quaternion newRotation = Quaternion.LookRotation(direction,Vector3.up); transform.rotation = Quaternion.Lerp(transform.rotation,newRotation,Time.deltaTime * 4f); transform.position = transform.position + direction * 3 * Time.deltaTime; } break; case "GoalSitInChair": GoalSitInChair goalSitInChair = nextGoal as GoalSitInChair; _currentChair = goalSitInChair.chair; break; case "GoalOrderCoffee": if ( Time.time < placedOrderAt ) { placedOrderAt = Time.time; } if ( Time.time > placedOrderAt + 3f) { hasOrdered = true; } break; case "GoalDrinkCoffee": if ( Time.time < startedDrinkingCoffeeAt ) { startedDrinkingCoffeeAt = Time.time; } if ( Time.time > startedDrinkingCoffeeAt + 5f) { hasDrunkCoffee = true; } break; case "GoalSitInNearestChair": GoalSitInNearestChair goalSitInNearestChair = nextGoal as GoalSitInNearestChair; _currentChair = goalSitInNearestChair.chair; break; } } }
public MoveAdjacentTo(Actor self, Target target) { this.target = target; mobile = self.Trait<Mobile>(); pathFinder = self.World.WorldActor.Trait<PathFinder>(); domainIndex = self.World.WorldActor.TraitOrDefault<DomainIndex>(); movementClass = (uint)mobile.Info.GetMovementClass(self.World.TileSet); repath = true; }
public void PathFinderDoesNotFindThePathForSmallBoard(int boardSize,int x, int y) { var board = new Board(boardSize, boardSize); var initialCoordintates = new Vector(x, y); var knight = new Knight(initialCoordintates, board); var pathFinder = new PathFinder(knight); var result = pathFinder.FindPath(); Assert.That(result, Is.EqualTo(false)); }
public void EverythingOk() { XmlDocument roadMapXmlDocument = new XmlDocument(); roadMapXmlDocument.Load(@".\UnitTests\TestXmlData\test-everything-is-ok.xml"); RoadMap roadMap = XmlRoadDataParser.ParseRoadMapXml(roadMapXmlDocument); Assert.AreNotEqual(roadMap, null); PathFinder pathFinder = new PathFinder(roadMap); List<RoadPath> paths = pathFinder.FindAllPaths().OrderBy(p => p.Length).ToList(); Assert.AreEqual(paths.Count, 7); Assert.AreEqual(paths[0].Length, 22); Assert.AreEqual(paths[0].ToList()[0].Id, 1); Assert.AreEqual(paths[0].ToList()[1].Id, 6); Assert.AreEqual(paths[0].ToList()[2].Id, 8); Assert.AreEqual(paths[0].ToList()[3].Id, 9); Assert.AreEqual(paths[0].ToList()[4].Id, 10); Assert.AreEqual(paths[1].Length, 25); Assert.AreEqual(paths[2].Length, 28); Assert.AreEqual(paths[3].Length, 35); Assert.AreEqual(paths[4].Length, 38); Assert.AreEqual(paths[4].ToList()[0].Id, 1); Assert.AreEqual(paths[4].ToList()[1].Id, 6); Assert.AreEqual(paths[4].ToList()[2].Id, 8); Assert.AreEqual(paths[4].ToList()[3].Id, 9); Assert.AreEqual(paths[4].ToList()[4].Id, 5); Assert.AreEqual(paths[4].ToList()[5].Id, 4); Assert.AreEqual(paths[4].ToList()[6].Id, 10); Assert.AreEqual(paths[5].Length, 58); Assert.AreEqual(paths[6].Length, 59); Assert.AreEqual(paths[6].ToList()[0].Id, 1); Assert.AreEqual(paths[6].ToList()[1].Id, 2); Assert.AreEqual(paths[6].ToList()[2].Id, 3); Assert.AreEqual(paths[6].ToList()[3].Id, 4); Assert.AreEqual(paths[6].ToList()[4].Id, 5); Assert.AreEqual(paths[6].ToList()[5].Id, 6); Assert.AreEqual(paths[6].ToList()[6].Id, 8); Assert.AreEqual(paths[6].ToList()[7].Id, 9); Assert.AreEqual(paths[6].ToList()[8].Id, 10); }
public void Test_WithClosedWall_CannotFindPath() { // Arrange AddWallWithoutGap(); PathFinder pathFinder = new PathFinder(searchParameters); // Act List<Point> path = pathFinder.FindPath(); // Assert Assert.IsNotNull(path); Assert.IsFalse(path.Any()); }
public void Test_WithoutWalls_CanFindPath() { // Arrange PathFinder pathFinder = new PathFinder(searchParameters); // Act List<Point> path = pathFinder.FindPath(); // Assert Assert.IsNotNull(path); Assert.IsTrue(path.Any()); Assert.AreEqual(4, path.Count); }
public GameWorld(Map map) { gameMap = map; playersOnline = new Dictionary<string, Player>(); creaturesOnline = new Dictionary<uint, Creature>(); eventHandler = new EventHandler(); eventHandler.World = this; eventHandler.Start(); lockThis = new Object(); chatSystem = new ChatSystem(map, playersOnline); pathFinder = new PathFinder(map); movingSystem = new MovingSystem(map, this); spellSystem = new SpellSystem(map); }
public void NoPathAtAll() { XmlDocument roadMapXmlDocument = new XmlDocument(); roadMapXmlDocument.Load(@".\UnitTests\TestXmlData\test-no-path-at-all.xml"); RoadMap roadMap = XmlRoadDataParser.ParseRoadMapXml(roadMapXmlDocument); Assert.AreNotEqual(roadMap, null); PathFinder pathFinder = new PathFinder(roadMap); List<RoadPath> paths = pathFinder.FindAllPaths().OrderBy(p => p.Length).ToList(); Assert.AreEqual(paths.Count, 0); }
public MoveAdjacentTo(Actor self, Target target) { this.target = target; mobile = self.Trait<Mobile>(); pathFinder = self.World.WorldActor.Trait<PathFinder>(); domainIndex = self.World.WorldActor.Trait<DomainIndex>(); movementClass = (uint)mobile.Info.GetMovementClass(self.World.TileSet); if (target.IsValidFor(self)) targetPosition = self.World.Map.CellContaining(target.CenterPosition); repath = true; }
public void Test_WithOpenWall_CanFindPathAroundWall() { // Arrange AddWallWithGap(); PathFinder pathFinder = new PathFinder(searchParameters); // Act List<Point> path = pathFinder.FindPath(); // Assert Assert.IsNotNull(path); Assert.IsTrue(path.Any()); Assert.AreEqual(5, path.Count); }
public override void SetUp() { Params.Load("default.properties"); targetPos = new Vector3(20, 0, -150); startPos = new Vector3(10, 0, 20); List<Entity> children = XNAGame.Instance.Children; fighter = new Fighter(); fighter.Position = startPos; children.Add(fighter); Obstacle obstacle = new Obstacle(10); obstacle.Position = new Vector3(15, 0, -10); children.Add(obstacle); obstacle = new Obstacle(12); obstacle.Position = new Vector3(5, 0, -50); children.Add(obstacle); obstacle = new Obstacle(5); obstacle.Position = new Vector3(15, 0, -70); children.Add(obstacle); pathFinder = new PathFinder(); Path path = pathFinder.FindPath(fighter.Position, targetPos); path.DrawPath = true; path.Looped = false; fighter.Path = path; XNAGame.Instance.Leader = fighter; fighter.SteeringBehaviours.turnOn(SteeringBehaviours.behaviour_type.follow_path); Fighter camFighter = new Fighter(); camFighter.Leader = fighter; camFighter.offset = new Vector3(0, 0, 5); camFighter.Position = fighter.Position + camFighter.offset; camFighter.SteeringBehaviours.turnOn(SteeringBehaviours.behaviour_type.offset_pursuit); camFighter.SteeringBehaviours.turnOn(SteeringBehaviours.behaviour_type.wall_avoidance); camFighter.SteeringBehaviours.turnOn(SteeringBehaviours.behaviour_type.obstacle_avoidance); XNAGame.Instance.CamFighter = camFighter; children.Add(camFighter); foreach (Entity child in children) { child.LoadContent(); } oldState = Keyboard.GetState(); }
private void CalcPath() { PathFinder<VoxelNode> pather = new PathFinder<VoxelNode>(VoxelGraph.Instance, VoxelEdge.MakeEdge); pather.Start = new VoxelNode(new Vector2i((int)pos1.x, (int)pos1.y)); pather.End = new VoxelNode(new Vector2i((int)pos2.x, (int)pos2.y)); pather.FindPath(); path = pather.CurrentPath.ToList(); if (Elve != null) { Elve.StartPath(pos2); } }
// Use this for initialization void Start() { base.Start(); pathFinder = GetComponent<PathFinder>(); pathFinder.Grid = grid; pathFinder.DistanceCanJump = heightCanJump; pathFinder.HeightCanJump = distanceCanJump; pathFinder.MaxDistance = maxSearchDistance; holder = GetComponent<KeyHolder>(); holder.OnKeyPickedUp += KeyPickedUp; trans = transform; }
void Start() { detSize = 21; pf = gameObject.AddComponent<PathFinder> (); pf.Initiate (detSize); awake = true; list = new List<Vector2> (); destTemp = transform.position; distDest = 0; speed = 2f; pfFlag = true; refreshRate = 1; }
//IThreadPoolWorkBatcherMember public void PerformWork(object context) { WorkContext con = (WorkContext)context; Vector3[] points = con.points; int depth = con.depth; SetBase(con.agent); HashSet <BattleGridPoint> result = new HashSet <BattleGridPoint>(); for (int i = 0; i < points.Length; i++) { Cell cellStart; if (PathFinder.TryGetClosestCell(points[i], agent.properties, out cellStart) == false) { continue; } Graph curGraph = cellStart.graph; if (curGraph != null && curGraph.battleGrid != null) { result.Add(curGraph.battleGrid.GetClosestPoint(points[i])); } } HashSet <BattleGridPoint> lastIteration = new HashSet <BattleGridPoint>(); foreach (var item in result) { lastIteration.Add(item); } HashSet <BattleGridPoint> curIteration; for (int i = 0; i < depth; i++) { curIteration = new HashSet <BattleGridPoint>(); foreach (var item in lastIteration) { foreach (var nb in item.neighbours) { if (nb == null) { continue; } if (result.Add(nb)) { curIteration.Add(nb); } } } lastIteration = curIteration; } agent.RecieveBattleGrid(result); if (con.callBack != null) { con.callBack.Invoke(); } }
protected string MakeMove() { var watch = new MultiWatch(); watch.Start("total"); var pathFinder = new PathFinder(ServerStuff.Board, ServerStuff.BoardSize); var tiles = ServerStuff.Board; var size = ServerStuff.BoardSize; var hero = ServerStuff.myHero.Pos; var id = ServerStuff.myHero.Id; watch.Measure("pathfinder Init", () => pathFinder.Init(hero)); //pathFinder.PrintMap(); Pos target; watch.Start("nearest"); var tavern = FindNearest(tiles, pathFinder, x => x.Type == TileType.TAVERN); var neutralMine = FindNearest(tiles, pathFinder, x => x.Type == TileType.GOLD_MINE_NEUTRAL); var notMineMine = FindNearest(tiles, pathFinder, x => x.Type >= TileType.GOLD_MINE_NEUTRAL && x.Type != TileType.GOLD_MINE_NEUTRAL + id); var enemy = FindNearest(tiles, pathFinder, x => x.Type >= TileType.HERO_1 && x.Type <= TileType.HERO_4 && x.Type != TileType.FREE + id); watch.Stop("nearest"); watch.Start("dist"); var enemyDist = pathFinder.GetDistance(enemy); var tavernDist = pathFinder.GetDistance(tavern); watch.Stop("dist"); //Console.WriteLine($"Tavern: {tavern}, neutral: {neutralMine}, notMine: {notMineMine}"); var dir = Direction.Stay; if (ServerStuff.myHero.Life < 30) { target = tavern; } else if (ServerStuff.myHero.Life < 80 && tavern != null && tavernDist < 2) { target = tavern; } else if (enemyDist < 2) { target = enemy; } else { target = notMineMine; } if (target == null) { //Console.WriteLine("I would stay"); } else { dir = watch.Measure("getDirection", () => pathFinder.GetDirection(target)); //Console.WriteLine($"I want to go from {hero.X}:{hero.Y} to {target.X}:{target.Y} using {dir}"); } watch.Stop("total"); //Console.WriteLine(string.Join(",", watch.Marks.Select(x => $"{x.Item1}:{x.Item2}"))); return(dir); }
void Start() { _agent = GetComponent <PathFinderAgent>(); _properties = _agent.properties; PathFinder.QueueGraph(new Bounds(transform.position, Vector3.one * 20), _properties); //queue some space in advance _controler = GetComponent <CharacterController>(); _agent.SetRecieveBattleGridDelegate((IEnumerable <BattleGridPoint> points) => { //take some values float agentHeight = _properties.height; int layers = _properties.includedLayers; Vector3 testTarget = target.transform.position; //update small list with subdivisions _heightTests.Clear(); for (int i = 0; i < sightSubdivisions; i++) { _heightTests.Add(1f - (1f / sightSubdivisions * i)); } BattleGridPoint targetPoint = null; float highestValue = 0; //debug int pointsLength = points.Count(); Vector3[] meshVerts = new Vector3[pointsLength * 4]; int[] meshTris = new int[pointsLength * 6]; int debugIndex = 0; foreach (var point in points) { //take point position and raycast to it in different heights to test visibility float value = 1f; for (int v = 0; v < _heightTests.Count; v++) { if (Physics.Linecast(testTarget, point.positionV3 + (Vector3.up * _heightTests[v] * agentHeight), layers) == false) { value = _heightTests[v]; } else { break; } } //multipy it by normalized distance to point. 1f is closest and 0f is farthest value *= Mathf.Clamp01((10 - Vector3.Distance(transform.position, point.positionV3)) / 10); if (value > highestValue) { highestValue = value; targetPoint = point; } //debug //drawing lots of small lines to debug this value. //cause Debuger_K dont exist in builded project for reasons Vector3 cameraKeyPoint = Vector3.Cross(cam.transform.position - point.positionV3, Vector3.up).normalized; meshVerts[debugIndex * 4] = point.positionV3 + (cameraKeyPoint * -debugWidth); //LB meshVerts[debugIndex * 4 + 1] = point.positionV3 + (cameraKeyPoint * debugWidth); //RB meshVerts[debugIndex * 4 + 2] = point.positionV3 + (cameraKeyPoint * -debugWidth) + new Vector3(0, value * debugHeight, 0); //LT meshVerts[debugIndex * 4 + 3] = point.positionV3 + (cameraKeyPoint * debugWidth) + new Vector3(0, value * debugHeight, 0); //RT meshTris[debugIndex * 6 + 0] = debugIndex * 4 + 1; meshTris[debugIndex * 6 + 1] = debugIndex * 4 + 0; meshTris[debugIndex * 6 + 2] = debugIndex * 4 + 2; meshTris[debugIndex * 6 + 3] = debugIndex * 4 + 1; meshTris[debugIndex * 6 + 4] = debugIndex * 4 + 2; meshTris[debugIndex * 6 + 5] = debugIndex * 4 + 3; debugIndex++; } //also debug Mesh mesh = new Mesh(); mesh.vertices = meshVerts; mesh.triangles = meshTris; _meshFilter.mesh = mesh; //send agent to this point if (targetPoint != null) { _agent.SetGoalMoveHere(targetPoint.positionV3); } }, AgentDelegateMode.ThreadSafe);//to shure it's in main thread StartCoroutine(UpdateBattleGridCall()); _debugGO = new GameObject("debug battle grid GO"); _debugMeshRenderer = _debugGO.AddComponent <MeshRenderer>(); _meshFilter = _debugGO.AddComponent <MeshFilter>(); _debugMeshRenderer.material = debugMaterial; }
public bool Act(Monster monster, CommandSystem commandSystem, Game game) { DungeonMap dungeonMap = game.World; Player player = game.Player; FieldOfView monsterFov = new FieldOfView(dungeonMap); // If the monster has not been alerted, compute a field-of-view // Use the monster's Awareness value for the distance in the FoV check // If the player is in the monster's FoV then alert it // Add a message to the MessageLog regarding this alerted status if (!monster.TurnsAlerted.HasValue) { monsterFov.ComputeFov(monster.X, monster.Y, monster.Awareness, true); if (monsterFov.IsInFov(player.X, player.Y)) { game.MessageLog.Add(monster.Name + " spots you."); monster.TurnsAlerted = 1; game.Player.EngageCombat(monster); } } if (monster.TurnsAlerted.HasValue) { // Before we find a path, make sure to make the monster and player Cells walkable dungeonMap.SetIsWalkable(monster.X, monster.Y, true); dungeonMap.SetIsWalkable(player.X, player.Y, true); PathFinder pathFinder = new PathFinder(dungeonMap, 1d); Path path = null; try { path = pathFinder.ShortestPath( dungeonMap.GetCell(monster.X, monster.Y), dungeonMap.GetCell(player.X, player.Y)); } catch (PathNotFoundException) { // The monster can see the player, but cannot find a path to him // This could be due to other monsters blocking the way // Add a message to the message log that the monster is waiting //game.MessageLog.Add(monster.Name + " waits for a turn."); } // Don't forget to set the walkable status back to false dungeonMap.SetIsWalkable(monster.X, monster.Y, false); dungeonMap.SetIsWalkable(player.X, player.Y, false); // In the case that there was a path, tell the CommandSystem to move the monster if (path != null) { if (path.Length > 1 && Game.Random.Next(100) < 25) { // teleport Rectangle teleportArea = new Rectangle(player.X - 3, player.Y - 3, 6, 6); Point p = dungeonMap.GetRandomWalkableLocationInRoom(teleportArea); game.MessageLog.Add("" + monster.Name + " teleports."); monster.X = p.X; monster.Y = p.Y; monster.MovesCompleted = monster.Moves; } else { try { // TODO: This should be path.StepForward() but there is a bug in RogueSharp V3 // The bug is that a Path returned from a PathFinder does not include the source Cell commandSystem.MoveMonster(monster, path.StepForward() as Cell); } catch (NoMoreStepsException) { game.MessageLog.Add(monster.Name + " cannot move."); } } } monster.TurnsAlerted++; // Lose alerted status every 10 turns. // As long as the player is still in FoV the monster will stay alert // Otherwise the monster will quit chasing the player. if (monster.TurnsAlerted > 10) { if (!monsterFov.IsInFov(player.X, player.Y)) { game.Player.LeaveCombat(monster); } monster.TurnsAlerted = null; } } return(true); }
private void Start() { pathfinder = FindObjectOfType <PathFinder>(); FindAndFollowPath(); }
//MoveEnemy is called by the GameManger each turn to tell each Enemy to try to move towards the player. public void MoveEnemy(String tag) { //Declare variables for X and Y axis move directions, these range from -1 to 1. //These values allow us to choose between the cardinal directions: up, down, left and right. int xDir = 0; int yDir = 0; //create two cells for origin and goal Cell origin = new Cell(); Cell goal = new Cell(); //set coordinates to position of gameobject currently in use origin.coordinates = new Vector2(transform.position.x, transform.position.y); setEnemyLocations(true); //create pathfinder object PathFinder pathFinder = new PathFinder(); //check if the enemy being used is the healthenemy and there are still some damage objects left if (tag == "HealthEnemy" && GameObject.FindGameObjectWithTag("Damage") != null) { //create array of gameobjects GameObject[] gos; //find all damage gameObjects gos = GameObject.FindGameObjectsWithTag("Damage"); //check if closest method null if (closest() != null) { //check if the distance betweenthe player and the nearest damage tile is less then 5 if ((Mathf.Abs(target.position.x - closest().transform.position.x) + Mathf.Abs(target.position.y - closest().transform.position.y)) < 5) { //set goal coordinates to the player location goal.coordinates = new Vector2(target.position.x, target.position.y); } else { //set goal to the closest damage tile goal.coordinates = new Vector2(closest().transform.position.x, closest().transform.position.y); } } } //if there are no damage tiles or none that are free else { //set goal as the players location goal.coordinates = new Vector2(target.position.x, target.position.y); } //set pathfinder object using the orgin and goal cell, the bscript.board from boardManager pathFinder.FindPath(origin, goal, bScript.board, false); //store the pathfinding list List <Cell> list = pathFinder.CellsFromPath(); //if the list is bigger then zero if (list.Count > 0) { //add the first cell in the list to the vector Vector2 end = list[0].coordinates; //calulate the x and y to check which direction to move xDir = (int)end.x - (int)transform.position.x; yDir = (int)end.y - (int)transform.position.y; } //check if it is a speedenemy and if the list has two cells if (tag == "SpeedEnemy" && list.Count > 1) { Vector2 end = list[1].coordinates; //find the second cell //move it to the new location alowing the speed enemy to move two cells each turn AttemptMove <Player>((int)end.x - (int)transform.position.x, (int)end.y - (int)transform.position.y); } AttemptMove <Player>(xDir, yDir); setEnemyLocations(false); }
void Awake() { instance = this; grid = GetComponent <Grid>(); }
public bool Act(Monster monster, CommandSystem commandSystem, Game game) { DungeonMap dungeonMap = game.World; Player player = game.Player; FieldOfView monsterFov = new FieldOfView(dungeonMap); if (!(monster is Beholder)) { return(false); } Monster[] beholder = game.beholder; if (beholder[0] == null) { return(false); } if (!beholder[0].TurnsAlerted.HasValue) { monsterFov.ComputeFov(beholder[0].X, beholder[0].Y, beholder[0].Awareness, true); if (monsterFov.IsInFov(player.X, player.Y)) { game.MessageLog.Add(beholder[0].Name + " wants to eat you."); beholder[0].TurnsAlerted = 1; game.Player.EngageCombat(beholder[0]); } } if (beholder[0].TurnsAlerted.HasValue) { // Can attack with main body? for (int b = 0; b < 6; b++) { foreach (Point p in neighbors) { if (game.Player.X == beholder[b].X + p.X && game.Player.Y == beholder[b].Y + p.Y) { commandSystem.Attack(beholder[0], game.Player); beholder[0].MovesCompleted = beholder[0].Moves; break; // only attack once with main } } } if ((beholder[0].MovesCompleted < beholder[0].Moves)) { int closestSectionIndex = 0; int closestSectionDist = 10000; bool tentaclesGone = true; for (int b = 6; b < 9; b++) { if (beholder[b] != null) { tentaclesGone = false; } } for (int b = 0; b < 9; b++) { if (beholder[b] == null) { continue; } dungeonMap.SetIsWalkable(beholder[b].X, beholder[b].Y, true); int distToPlayer = Math.Max(Math.Abs(beholder[b].X - player.X), Math.Abs(beholder[b].Y - player.Y)); if (distToPlayer < closestSectionDist) { closestSectionIndex = b; } } dungeonMap.SetIsWalkable(player.X, player.Y, true); PathFinder pathFinder = new PathFinder(dungeonMap, 1d); Path path = null; try { path = pathFinder.ShortestPath( dungeonMap.GetCell(beholder[closestSectionIndex].X, beholder[closestSectionIndex].Y), dungeonMap.GetCell(player.X, player.Y)); } catch (PathNotFoundException) { } dungeonMap.SetIsWalkable(player.X, player.Y, false); if (path != null) { try { Cell cell = path.StepForward() as Cell; int dX = cell.X - beholder[closestSectionIndex].X; int dY = cell.Y - beholder[closestSectionIndex].Y; if (game.World.CanRectFitInRoom(new Rectangle(beholder[0].X + dX, beholder[0].Y + dY, 3, (tentaclesGone) ? 2 : 3))) { for (int b = 0; b < 9; b++) { if (beholder[b] == null) { continue; } beholder[b].X = beholder[b].X + dX; beholder[b].Y = beholder[b].Y + dY; //game.World.SetIsWalkable(beholder[b].X, beholder[b].Y, false); } } } catch (NoMoreStepsException) { game.MessageLog.Add(beholder[0].Name + " is stuck."); } } for (int b = 0; b < 9; b++) { if (beholder[b] == null) { continue; } dungeonMap.SetIsWalkable(beholder[b].X, beholder[b].Y, false); } } beholder[0].TurnsAlerted++; if (monster.TurnsAlerted > 10) { if (!monsterFov.IsInFov(player.X, player.Y)) { game.Player.LeaveCombat(beholder[0]); } beholder[0].TurnsAlerted = null; } } return(true); }
// Use this for initialization void Start() { PathFinder.createMatrix(); resetPosition(); }
void Awake() { enemy = GetComponent <Enemy>(); gridManager = FindObjectOfType <GridManager>(); pathFinder = FindObjectOfType <PathFinder>(); }
public TestAStar(PathFinder <WeightedPath> finder) { this._finder = finder; }
public bool TryToFindPathWithGraph(Vector2 start, Vector2 end, ZoneMap zoneMap) { try { PathFinder pathFinder = new PathFinder(); pathFindingIndex = 0; currentPathInPoEGridCoordinates.Clear(); const int radius = 7; /* If the player is too close to obstacles a path might not be found. * Shift the player "coordinate" away from obstacle */ //int maxAttemptsToFindAPath = 4 var royTGraphPosStart = zoneMap.PoEGridPositionToRoyTPathFindingGraphPosition(start); var royTGraphPosEnd = zoneMap.PoEGridPositionToRoyTPathFindingGraphPosition(end); var nodeDictionary = zoneMap.GetSubMap(start).NodeDictionary; Node startNode = TryGetValidNodeAroundGridPos(zoneMap, nodeDictionary, start); Node endNode = TryGetValidNodeAroundGridPos(zoneMap, nodeDictionary, end); //bool gotStartNode = zoneMap.GetSubMap(start).NodeDictionary.TryGetValue(royTGraphPosStart, out startNode); //bool gotEndNode = zoneMap.GetSubMap(start).NodeDictionary.TryGetValue(royTGraphPosEnd, out endNode); if (startNode == null || endNode == null) { Console.WriteLine("Unable to find correct navigation grid"); return(false); } if (startNode == endNode) { Console.WriteLine("Nodes are equal. abort"); return(false); } while (true) { var path = pathFinder.FindPath(startNode, endNode, Velocity.FromKilometersPerHour(100000)); if (path == null || path.Edges.Count == 0) // || path.Type == PathType.ClosestApproach) { Console.WriteLine("Unable to find a path with given start/end, randomizing start/end"); int xRandom = MathHepler.Randomizer.Next((int)start.X - radius, (int)start.X + radius); int yRandom = MathHepler.Randomizer.Next((int)start.Y - radius, (int)start.Y + radius); startNode = TryGetValidNodeAroundGridPos(zoneMap, nodeDictionary, new Vector2(xRandom, yRandom)); xRandom = MathHepler.Randomizer.Next((int)end.X - radius, (int)end.X + radius); yRandom = MathHepler.Randomizer.Next((int)end.Y - radius, (int)end.Y + radius); endNode = TryGetValidNodeAroundGridPos(zoneMap, nodeDictionary, new Vector2(xRandom, yRandom)); } else { RemainingPathDistanceSquaredToTarget = 0; int counter = 0; var previousEdgeVector = new Vector2(); foreach (var edge in path.Edges) { var compensatedEdgeVector = new Vector2(edge.Start.Position.X * PathfindingConsts.myPathfindingGridSize, edge.Start.Position.Y * PathfindingConsts.myPathfindingGridSize); if (counter != 0) { var distance = previousEdgeVector.Distance(compensatedEdgeVector); RemainingPathDistanceSquaredToTarget += distance; } currentPathInPoEGridCoordinates.Add(compensatedEdgeVector); previousEdgeVector = compensatedEdgeVector; counter += 1; } RemainingPathDistanceSquaredToTarget = RemainingPathDistanceSquaredToTarget * RemainingPathDistanceSquaredToTarget; return(true); } } } catch { return(false); } }
internal XcStudio(ICakeContext context, Platform platform) { _xcStudioPath = new PathFinder(context.Log).FindXcStudio(platform); _xcStudioProgram = PathFinder.GetXcStudioProgram(platform); }
void Update() { //Movement if (Input.GetMouseButton(1)) { rot = new Vector2( rot.x + Input.GetAxis("Mouse X") * 3, rot.y + Input.GetAxis("Mouse Y") * 3 ); cam.transform.localRotation = Quaternion.AngleAxis(rot.x, Vector3.up); cam.transform.localRotation *= Quaternion.AngleAxis(rot.y, Vector3.left); } bool turbo = Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift); cam.transform.position += cam.transform.forward * 40 * (turbo ? 3 : 1) * Input.GetAxis("Vertical") * Time.deltaTime; cam.transform.position += cam.transform.right * 40 * (turbo ? 3 : 1) * Input.GetAxis("Horizontal") * Time.deltaTime; //Save saveProgressText.text = saveProgress != null?SaveStatus() : "Save"; var mousePos = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)); ushort type = world.blockProvider.GetType(blockToPlace); VmRaycastHit hit = Code.Voxelmetric.Raycast(new Ray(cam.transform.position, mousePos - cam.transform.position), world, 100, type == BlockProvider.AirType); selectedBlockText.text = Code.Voxelmetric.GetBlock(world, hit.vector3Int).displayName; if (Input.GetMouseButtonDown(0) && !eventSystem.IsPointerOverGameObject()) { if (hit.block.type != BlockProvider.AirType) { bool adjacent = type != BlockProvider.AirType; Code.Voxelmetric.SetBlock(world, adjacent ? hit.adjacentPos : hit.vector3Int, new BlockData(type)); } } if (Input.GetKeyDown(KeyCode.I)) { pfStart = hit.vector3Int; } if (Input.GetKeyDown(KeyCode.O)) { pfStop = hit.vector3Int; } if (Input.GetKeyDown(KeyCode.P)) { pf = new PathFinder(pfStart, pfStop, world, 2); Debug.Log(pf.path.Count); } if (pf != null && pf.path.Count != 0) { for (int i = 0; i < pf.path.Count - 1; i++) { Debug.DrawLine(pf.path[i].Add(0, 1, 0), pf.path[i + 1].Add(0, 1, 0)); } } }
void Awake() { pathFinder = GetComponent <PathFinder>(); enemyPlayer = GetComponent <EnemyPlayer>(); }
public override void Run() { int currentPoint; float pathIdentity = Math.DistanceListPoint(PathLoop); if (_loopPathId != pathIdentity) // If path changed, then we need to find the nearest point { currentPoint = Math.NearestPointOfListPoints(PathLoop, ObjectManager.ObjectManager.Me.Position); MovementManager.PointId = currentPoint; } // If the path did not change, let's find a good next point else if (PathLoop[MovementManager.PointId].DistanceTo(ObjectManager.ObjectManager.Me.Position) > 2.0f) { currentPoint = MovementManager.PointId + 1; if (currentPoint > PathLoop.Count - 1) { currentPoint = 0; } int point = currentPoint; int lookup = 0; Vector3 me = new Vector3(ObjectManager.ObjectManager.Me.Position); do { int pointNext = (point + 1 <= PathLoop.Count - 1 ? point + 1 : 0); Vector3 v0 = new Vector3(PathLoop[point]); Vector3 v1 = new Vector3(PathLoop[pointNext]); float angle = (v1 - v0).Angle2D(v0 - me); if (System.Math.Abs(angle) <= (System.Math.PI / 3f)) { Logging.WriteNavigator("Next Point is " + (point - currentPoint) + " ahead, his angle is " + System.Math.Round(angle * 180 / System.Math.PI, 2) + "°"); currentPoint = point; break; } point = pointNext; lookup++; } while (lookup <= 10); MovementManager.PointId = currentPoint; } else { currentPoint = MovementManager.PointId; } if (_loopPathId == -1f) { _loopPathId = pathIdentity; } // Too far away, then we don't care for fly/swim but we need pathfinder to go by foot before anything else // This simply does not work. Grinder for low level (on ground) still go straitline in front for long distance if (PathLoop[currentPoint].Type.ToLower() != "flying" && PathLoop[currentPoint].Type.ToLower() != "swimming" && PathLoop[currentPoint].DistanceTo2D(ObjectManager.ObjectManager.Me.Position) > 7 /*&& * PathLoop[_currentPoint].DistanceTo2D(ObjectManager.ObjectManager.Me.Position) <= 200*/) { bool bResult; List <Point> npoints = PathFinder.FindPath(PathLoop[currentPoint], out bResult); if (!bResult) { npoints.Add(new Point(PathLoop[currentPoint])); } MovementManager.Go(npoints); return; } // We are near enough or flying/swimming then restore the loop MovementManager.GoLoop(PathLoop); }
public override void OnTrigger(GameClient session, RoomItem item, int request, bool hasRights) { if (session == null) { return; } RoomUser roomUserByHabbo = item.GetRoom().GetRoomUserManager().GetRoomUserByHabbo(session.GetHabbo().Id); if (roomUserByHabbo == null) { return; } if (PathFinder.GetDistance(roomUserByHabbo.X, roomUserByHabbo.Y, item.X, item.Y) > 1) { roomUserByHabbo.MoveTo(item.X + 1, item.Y); } if (Math.Abs(roomUserByHabbo.X - item.X) < 2 && Math.Abs(roomUserByHabbo.Y - item.Y) < 2) { roomUserByHabbo.SetRot( PathFinder.CalculateRotation(roomUserByHabbo.X, roomUserByHabbo.Y, item.X, item.Y), false); Room room = item.GetRoom(); Point point = new Point(0, 0); switch (roomUserByHabbo.RotBody) { case 4: point = new Point(item.X, item.Y + 1); break; case 0: point = new Point(item.X, item.Y - 1); break; case 6: point = new Point(item.X - 1, item.Y); break; default: if (roomUserByHabbo.RotBody != 2) { return; } point = new Point(item.X + 1, item.Y); break; } if (!room.GetGameMap().ValidTile2(point.X, point.Y)) { return; } List <RoomItem> coordinatedItems = room.GetGameMap().GetCoordinatedItems(point); if (coordinatedItems.Any(i => !i.GetBaseItem().Stackable)) { return; } double num = item.GetRoom().GetGameMap().SqAbsoluteHeight(point.X, point.Y); ServerMessage serverMessage = new ServerMessage(); serverMessage.Init(LibraryParser.OutgoingRequest("ItemAnimationMessageComposer")); serverMessage.AppendInteger(item.X); serverMessage.AppendInteger(item.Y); serverMessage.AppendInteger(point.X); serverMessage.AppendInteger(point.Y); serverMessage.AppendInteger(1); serverMessage.AppendInteger(item.Id); serverMessage.AppendString(item.Z.ToString(Yupi.CultureInfo)); serverMessage.AppendString(num.ToString(Yupi.CultureInfo)); serverMessage.AppendInteger(0); room.SendMessage(serverMessage); item.GetRoom() .GetRoomItemHandler() .SetFloorItem(roomUserByHabbo.GetClient(), item, point.X, point.Y, item.Rot, false, false, false); } }
public AICommand BuildCommand(Unit unit) { if (isFirstMove) { isFirstMove = false; return(AICommand.BuildMoveCommand(unit, unit.NextMove())); } else if (!unit.HasPath) { int Xincrementer = 2; int Yincrementer = 2; // var tileLocation = unit.Location; // tileLocation.X = tileLocation.X * incrementer; // tileLocation.Y = tileLocation.Y * incrementer; PathFinder pF = new PathFinder(Map); unit.Path = pF.FindPath(unit.Location, (unit.Location.X * Xincrementer, unit.Location.Y * Yincrementer)); while (Yincrementer < 3 && !unit.HasPath) { // tileLocation.X = tileLocation.X + 1; // tileLocation.Y = tileLocation.Y + 1; Yincrementer = Yincrementer + 1; Xincrementer = Xincrementer + 1; unit.Path = pF.FindPath(unit.Location, (unit.Location.X, unit.Location.Y * Yincrementer)); } while (Xincrementer < 3 && !unit.HasPath) { // tileLocation.X = tileLocation.X + 1; // tileLocation.Y = tileLocation.Y + 1; Yincrementer = Yincrementer + 1; Xincrementer = Xincrementer + 1; unit.Path = pF.FindPath(unit.Location, (unit.Location.X * Xincrementer, unit.Location.Y)); } while (Xincrementer < 3 && Yincrementer < 5 && !unit.HasPath) { // tileLocation.X = tileLocation.X + 1; // tileLocation.Y = tileLocation.Y + 1; Yincrementer = Yincrementer + 1; Xincrementer = Xincrementer + 1; unit.Path = pF.FindPath(unit.Location, (unit.Location.X * Xincrementer, unit.Location.Y * Yincrementer)); } return(AICommand.BuildMoveCommand(unit, unit.NextMove())); } else { return(AICommand.BuildMoveCommand(unit, unit.NextMove())); } // if (!unit.HasPath) { // PathFinder pF = new PathFinder(Map); // unit.Path = pF.FindPath(unit.Location, (1000, 1000)); // return AICommand.BuildMoveCommand(unit, unit.NextMove()); // } else { // return AICommand.BuildMoveCommand(unit, unit.NextMove()); // } }
public void UpdateMouseWithLogicalCell(VectorInt2 cell, bool isLeftDown, bool isRightDown) { if (!Game.Current.Contains(cell)) { return; } peekMovePath = null; peekCratePath = null; try { if (isLeftDown && !prevLeftDown) { Drag(cell); return; } if (!isLeftDown && prevLeftDown) { Drop(cell); return; } var peek = Peek(cell); if (peek != Action.None) { if (peek == Action.Move) { start = Game.Current.Player.Position; var end = cell; var boundry = Game.Current.ToMap(Game.Current.Definition.Wall, Game.Current.Definition.Crate, Game.Current.Definition.CrateGoal); peekMovePath = PathFinder.Find(boundry, start, end); } else if (peek == Action.Drag) { var end = cell; var state = Game.Analysis.Evalute(Game.Current); var pushMap = PushMap.Find(state.Static, state.Current, start, Game.Current.Player.Position); if (pushMap.CrateMap[end]) { //var walk = pushMap.FindPlayerWalkRoute(end); peekCratePath = pushMap.FindCrateRoute(end); // PLayer move to begin crate stuff var pstart = Game.Current.Player.Position; var pend = start - peekCratePath.First(); var boundry = Game.Current.ToMap(Game.Current.Definition.Wall, Game.Current.Definition.Crate, Game.Current.Definition.CrateGoal); peekMovePath = PathFinder.Find(boundry, pstart, pend); if (peekMovePath != null) { peekMovePath.Add(peekCratePath.First()); } } } } } finally { prev = cell; prevLeftDown = isLeftDown; prevRightDown = isRightDown; } }
public static void Pulse(IEnumerable <WoWUnit> woWUnits) { try { woWUnits = woWUnits.OrderBy(x => x.GetDistance); foreach (WoWUnit wowUnit in woWUnits) { try { if (Products.Products.IsStarted) { if (nManagerSetting.IsBlackListed(wowUnit.Guid)) { continue; } MovementManager.StopMove(); MovementManager.StopMove(); Thread.Sleep(250 + Usefuls.Latency); while (ObjectManager.ObjectManager.Me.IsCast) { Thread.Sleep(200); } if (!wowUnit.IsValid) { continue; } bool looted = false; if (wowUnit.IsLootable) { Logging.Write("Loot " + wowUnit.Name); } else if (wowUnit.IsSkinnable && nManagerSetting.CurrentSetting.ActivateBeastSkinning) { Logging.Write("Skin " + wowUnit.Name); } else { continue; } FarmingTask.CurUnit = wowUnit; // We have no item to loot at range, then go to mob if (!CombatClass.InMeleeRange(wowUnit) && (!nManagerSetting.CurrentSetting.UseLootARange || LootARangeId == 0 || ObjectManager.ObjectManager.Me.Position.DistanceTo(wowUnit.Position) > 40f || !ItemsManager.IsItemUsable(LootARangeId))) { bool success; List <Point> points = PathFinder.FindPath(wowUnit.Position, out success); if (points.Count <= 0) { points.Add(ObjectManager.ObjectManager.Me.Position); points.Add(wowUnit.Position); } if (!success) { if ((points.Count == 2 && wowUnit.GetDistance > 6) || points.Count != 2) { // we didn't find a valid path and the target is not that close, blacklisting. // Straightline wont help anyway. Logging.Write("No path to " + wowUnit.Name + ", blacklisting."); nManagerSetting.AddBlackList(wowUnit.Guid, 1000 * 60 * 5); } } MovementManager.Go(points); Timer timer = new Timer((int)(Math.DistanceListPoint(points) / 3 * 1000) + 3000); while (!ObjectManager.ObjectManager.Me.IsDeadMe && wowUnit.IsValid && Products.Products.IsStarted && ObjectManager.ObjectManager.GetNumberAttackPlayer() == 0 && !(ObjectManager.ObjectManager.Me.InCombat && !(ObjectManager.ObjectManager.Me.IsMounted && (nManagerSetting.CurrentSetting.IgnoreFightIfMounted || Usefuls.IsFlying))) && !timer.IsReady) { if (ObjectManager.ObjectManager.Me.Position.DistanceTo(wowUnit.Position) <= 4.0f) { MovementManager.StopMove(); MovementManager.StopMove(); MountTask.DismountMount(); Thread.Sleep(250); while (ObjectManager.ObjectManager.Me.GetMove) { Thread.Sleep(50); } break; } } } // Now loot if (wowUnit.IsLootable) { // Code for 109167 Findle's Loot-A-Range and 60854 Loot-A-Rang if (nManagerSetting.CurrentSetting.UseLootARange && !CombatClass.InMeleeRange(wowUnit) && ObjectManager.ObjectManager.Me.Position.DistanceTo(wowUnit.Position) <= 40f && LootARangeId != 0 && ItemsManager.IsItemUsable(LootARangeId)) { // Since these items have a CD of only 3 sec, it's worth waiting for the CD to recover while (ItemsManager.IsItemOnCooldown(LootARangeId)) { Thread.Sleep(250); } FarmingTask.CountThisLoot = true; FarmingTask.NodeOrUnit = false; ItemsManager.UseToy(LootARangeId); Thread.Sleep(1000 + Usefuls.Latency); while (ObjectManager.ObjectManager.Me.IsCast) { if (ObjectManager.ObjectManager.Me.InCombat && !(ObjectManager.ObjectManager.Me.IsMounted && (nManagerSetting.CurrentSetting.IgnoreFightIfMounted || Usefuls.IsFlying))) { return; } Thread.Sleep(150); } } else { FarmingTask.CountThisLoot = true; FarmingTask.NodeOrUnit = false; Interact.InteractWith(wowUnit.GetBaseAddress); if ((ObjectManager.ObjectManager.Me.InCombat && !(ObjectManager.ObjectManager.Me.IsMounted && (nManagerSetting.CurrentSetting.IgnoreFightIfMounted || Usefuls.IsFlying)))) { return; } Thread.Sleep(500 + Usefuls.Latency); } if (nManagerSetting.CurrentSetting.ActivateBeastSkinning && ObjectManager.ObjectManager.GetNumberAttackPlayer() > 0) { return; } Statistics.Loots++; if (nManagerSetting.CurrentSetting.ActivateBeastSkinning) { Thread.Sleep(475 + Usefuls.Latency); // let the client react to unit flag change looted = true; } else { WoWUnit unit = wowUnit; // we blacklist all unit around for a short time to be sure we loot then foreach (WoWUnit u in woWUnits.Where(u => u != unit).Where(u => u.Position.DistanceTo2D(unit.Position) <= 25f)) { nManagerSetting.AddBlackList(u.Guid, 475 + Usefuls.Latency); } nManagerSetting.AddBlackList(wowUnit.Guid, 475 + Usefuls.Latency); return; } } if ((looted || !wowUnit.IsLootable) && !wowUnit.IsSkinnable) { continue; } // From here we are sure the unit is skinnable // if this is the unit we just looted, we need to redo check for extra loot // if this is NOT the unit we just looted, then the check is already done at list building time if (nManagerSetting.CurrentSetting.ActivateBeastSkinning && ObjectManager.ObjectManager.GetNumberAttackPlayer() == 0) { if ((looted || !wowUnit.IsLootable)) { if (wowUnit.ExtraLootType.HasFlag(TypeFlag.HERB_LOOT) || wowUnit.Entry == 112052 || wowUnit.Entry == 113646) { int myHerbalismLevel = Skill.GetValue(SkillLine.Herbalism); if (myHerbalismLevel <= 0) { nManagerSetting.AddBlackList(wowUnit.Guid, 1000 * 60 * 5); continue; } } else if (wowUnit.ExtraLootType.HasFlag(TypeFlag.MINING_LOOT) || wowUnit.Entry == 104895 || wowUnit.Entry == 104877) { int myMiningLevel = Skill.GetValue(SkillLine.Mining); if (myMiningLevel <= 0) { nManagerSetting.AddBlackList(wowUnit.Guid, 1000 * 60 * 5); continue; } } else if (wowUnit.ExtraLootType.HasFlag(TypeFlag.ENGENEERING_LOOT)) { int myEngineeringLevel = Skill.GetValue(SkillLine.Engineering); if (myEngineeringLevel <= 0) { nManagerSetting.AddBlackList(wowUnit.Guid, 1000 * 60 * 5); continue; } } else { int mySkinningLevel = Skill.GetValue(SkillLine.Skinning); if (mySkinningLevel <= 0) { nManagerSetting.AddBlackList(wowUnit.Guid, 1000 * 60 * 5); continue; } } } // If we looted at range, we must go to creature to skin it if (!CombatClass.InMeleeRange(wowUnit)) { List <Point> points = PathFinder.FindPath(wowUnit.Position); if (points.Count <= 0) { points.Add(ObjectManager.ObjectManager.Me.Position); points.Add(wowUnit.Position); } MovementManager.Go(points); Timer timer = new Timer((int)(Math.DistanceListPoint(points) / 3 * 1000) + 3000); while (!ObjectManager.ObjectManager.Me.IsDeadMe && wowUnit.IsValid && Products.Products.IsStarted && ObjectManager.ObjectManager.GetNumberAttackPlayer() == 0 && !(ObjectManager.ObjectManager.Me.InCombat && !(ObjectManager.ObjectManager.Me.IsMounted && (nManagerSetting.CurrentSetting.IgnoreFightIfMounted || Usefuls.IsFlying))) && !timer.IsReady) { if (CombatClass.InMeleeRange(wowUnit)) { MovementManager.StopMove(); MovementManager.StopMove(); MountTask.DismountMount(); Thread.Sleep(250); while (ObjectManager.ObjectManager.Me.GetMove) { Thread.Sleep(50); } break; } } } Logging.Write("Skin " + wowUnit.Name); Interact.InteractWith(wowUnit.GetBaseAddress); Thread.Sleep(200 + Usefuls.Latency); while (ObjectManager.ObjectManager.Me.IsCast) { Thread.Sleep(100); } if ((ObjectManager.ObjectManager.Me.InCombat && !(ObjectManager.ObjectManager.Me.IsMounted && (nManagerSetting.CurrentSetting.IgnoreFightIfMounted || Usefuls.IsFlying)))) { return; } Thread.Sleep(400 + Usefuls.Latency); if (nManagerSetting.CurrentSetting.ActivateBeastSkinning && ObjectManager.ObjectManager.GetNumberAttackPlayer() > 0) { return; } Statistics.Farms++; nManagerSetting.AddBlackList(wowUnit.Guid, 1000 * 60 * 5); } } MovementManager.StopMove(); MovementManager.StopMove(); } catch { } } } catch (Exception ex) { Logging.WriteError("LootingTask > Pulse(IEnumerable<WoWUnit> woWUnits): " + ex); } }
void Start() { // Load Controllers data = GameObject.FindWithTag("Data").GetComponent <PersistentData>(); animator = gameObject.GetComponent <Animator>(); // Load Map Controllers Grid grid = FindObjectOfType <Grid>(); foreach (Tilemap map in FindObjectsOfType <Tilemap>()) { if (map.name == "FloorMap") { floorMap = map; } else if (map.name == "LeftWallMap") { leftWallMap = map; } else if (map.name == "RightWallMap") { rightWallMap = map; } else if (map.name == "BlockMap") { blockMap = map; } } dungeonController = floorMap.GetComponent <DungeonController>(); if (dungeonController != null) { mapType = "Dungeon"; NotableCollide = dungeonController.NotableCollide; OpenDoor = dungeonController.OpenDoor; OpenChest = dungeonController.OpenChest; } villageController = floorMap.GetComponent <VillageController>(); if (villageController != null) { mapType = "Village"; NotableCollide = villageController.NotableCollide; OpenDoor = villageController.OpenDoor; FetchPosition = villageController.FetchPosition; } maps = new Dictionary <string, Tilemap>(); maps.Add("left", leftWallMap); maps.Add("right", rightWallMap); uiController = GameObject.Find("UICanvas").GetComponent <UIController>(); canvas = GameObject.FindWithTag("WorldCanvas"); // Load Resources walkNames = new string[4] { "walkUp", "walkRight", "walkDown", "walkLeft" }; attackNames = new string[4] { "attackUp", "attackRight", "attackDown", "attackLeft" }; targetPosition = this.transform.position; textFab = Resources.Load("Prefabs/DamageText") as GameObject; // Set Attributes tilePosition = new Vector3Int(0, 0, 0); if (FetchPosition != null) { tilePosition = FetchPosition(); Vector3 pos = PathFinder.TileToWorld(tilePosition); pos.y += 0.25f; transform.position = pos; animator.CrossFade(walkNames[data.direction], 0f); } entities = GameObject.FindWithTag("EntityList"); entityController = entities.GetComponent <EntityController>(); mainCamera = GameObject.FindWithTag("MainCamera"); Vector3 camVec = this.transform.position; camVec.z = -10; mainCamera.transform.position = camVec; facing = new string[2]; maxhp = 20; hp = data.playerHp; if (hp == 0) { hp = maxhp; } food = data.food; uiController.UpdateBars(); attack = 5; defense = 5; speed = 1; mindmg = 0; maxdmg = 0; armorDR = 0; EquipWeapon(data.weapon); if (data.armor != null) { EquipArmor(data.armor); } saySomething = ""; }
static Path FindMoveMapOrNull(Puzzle p, VectorInt2 start, VectorInt2 end) { var boundary = p.ToMap(p.Definition.Obsticles); return(PathFinder.Find(boundary, start, end)); }
// Start is called before the first frame update private void Awake() { pathFinder = GameObject.FindObjectOfType <PathFinder>(); }
private void Awake() { pathFinder = GetComponent <PathFinder>(); }
public bool Act(Monster monster, CommandSystem commandSystem) { GameMap map = Game.Map; Player player = Game.Player; FieldOfView monsterFov = new FieldOfView(map); // If the monster has not been alerted, compute a field-of-view // Use the monster's Awareness value for the distance in the FoV check // If the player is in the monster's FoV then alert it // Add a message to the MessageLog regarding this alerted status if (!monster.TurnsAlerted.HasValue) { monsterFov.ComputeFov(monster.X, monster.Y, monster.Awareness, true); if (monsterFov.IsInFov(player.X, player.Y)) { Game.MessageLog.Add($"{monster.Name} a envie de combattre {player.Name}"); monster.TurnsAlerted = 1; } } if (monster.TurnsAlerted.HasValue) { monsterFov.ComputeFov(monster.X, monster.Y, monster.Awareness, true); int deltaX = player.X - monster.X; int deltaY = player.Y - monster.Y; if (Math.Abs(deltaX) == 1 || Math.Abs(deltaY) == 1) { commandSystem.MoveMonster(monster, map.GetCell(monster.X - deltaX, monster.Y - deltaY)); return(true); } if (map.IsInFov(player.X, player.Y) && Math.Abs(deltaX) <= 3 && Math.Abs(deltaY) <= 3) { commandSystem.Attack(monster, player); return(true); } // Before we find a path, make sure to make the monster and player Cells walkable map.SetIsWalkable(monster.X, monster.Y, true); map.SetIsWalkable(player.X, player.Y, true); PathFinder pathFinder = new PathFinder(map); Path path = null; bool pathFound = true; try { path = pathFinder.ShortestPath(map.GetCell(monster.X, monster.Y), map.GetCell(player.X, player.Y)); } catch (PathNotFoundException) { // The monster can see the player, but cannot find a path to him // This could be due to other monsters blocking the way pathFound = false; } if (!pathFound) { // Add a message to the message log that the monster is waiting Game.MessageLog.Add($"{monster.Name} attend le prochain tour"); } // Don't forget to set the walkable status back to false map.SetIsWalkable(monster.X, monster.Y, false); map.SetIsWalkable(player.X, player.Y, false); // In the case that there was a path, tell the CommandSystem to move the monster if (path != null) { try { // Take the first step of the path commandSystem.MoveMonster(monster, path.StepForward()); } catch (NoMoreStepsException) { Game.MessageLog.Add($"{monster.Name} growls in frustration"); } } monster.TurnsAlerted++; // Lose alerted status every 15 turns. // As long as the player is still in FoV the monster will stay alert // Otherwise the monster will quit chasing the player. if (monster.TurnsAlerted > 15) { monster.TurnsAlerted = null; } } return(true); }
public static bool PathFinder_FindPath(IntVec3 start, LocalTargetInfo dest, TraverseParms traverseParms, PathEndMode peMode, PathFinder __instance, ref PawnPath __result) { Map map = getMap(__instance); __result = MyPathFinder.FindPath(start, dest, traverseParms, peMode, map); #if false Pawn pawn = traverseParms.pawn; if (pawn.Name != null) { string name = pawn.Name.ToString(); if (name == "name here") { Log.Error("TP mode: " + traverseParms.mode); map.debugDrawer.FlashCell(dest.Cell, 0.5f, "X", 100); if (__result.Found) { IntVec3 cellBeforeBlocker; Thing thing = __result.FirstBlockingBuilding(out cellBeforeBlocker, pawn); if (thing != null) { map.debugDrawer.FlashCell(cellBeforeBlocker, 0.8f, "X", 100); } List <IntVec3> cells = __result.NodesReversed; for (int i = 0; i < cells.Count; i++) { map.debugDrawer.FlashCell(cells[i], 0.9f, "X", 100); } } } } #endif return(false); }
// Start is called before the first frame update void Awake() { enemyScript = GetComponent <Enemy>(); graph = FindObjectOfType <Graph>(); pathFinder = FindObjectOfType <PathFinder>(); }
public TileMapEngine() { pathFinder = new PathFinder(new AStartAlogrithm()); }
void Start() { enemyBaseFinder = new PathFinder(); enemyWithFlagFinder = new PathFinder(); friendlyBaseFinder = new PathFinder(); }
public override void Process(uint seed) { List <PathList> pathLists = new List <PathList>(); TerrainHeightMap heightMap = TerrainMeta.HeightMap; TerrainTopologyMap topologyMap = TerrainMeta.TopologyMap; List <MonumentInfo> monuments = TerrainMeta.Path.Monuments; if (monuments.Count == 0) { return; } int num = Mathf.NextPowerOfTwo((int)((float)((float)World.Size) / 10f)); int[,] numArray = new int[num, num]; float single = 5f; for (int i = 0; i < num; i++) { float single1 = ((float)i + 0.5f) / (float)num; for (int j = 0; j < num; j++) { float single2 = ((float)j + 0.5f) / (float)num; float slope = heightMap.GetSlope(single2, single1); int topology = topologyMap.GetTopology(single2, single1, single); int num1 = 2295174; int num2 = 55296; int num3 = 512; if ((topology & num1) != 0) { numArray[i, j] = 2147483647; } else if ((topology & num2) != 0) { numArray[i, j] = 2500; } else if ((topology & num3) == 0) { numArray[i, j] = 1 + (int)(slope * slope * 10f); } else { numArray[i, j] = 1000; } } } PathFinder pathFinder = new PathFinder(numArray, true); List <GeneratePowerlineLayout.PathSegment> pathSegments = new List <GeneratePowerlineLayout.PathSegment>(); List <GeneratePowerlineLayout.PathNode> pathNodes = new List <GeneratePowerlineLayout.PathNode>(); List <GeneratePowerlineLayout.PathNode> pathNodes1 = new List <GeneratePowerlineLayout.PathNode>(); List <PathFinder.Point> points = new List <PathFinder.Point>(); List <PathFinder.Point> points1 = new List <PathFinder.Point>(); List <PathFinder.Point> points2 = new List <PathFinder.Point>(); foreach (MonumentInfo monument in monuments) { bool count = pathNodes.Count == 0; foreach (TerrainPathConnect target in monument.GetTargets(InfrastructureType.Power)) { PathFinder.Point point = target.GetPoint(num); PathFinder.Node node = pathFinder.FindClosestWalkable(point, 100000); if (node == null) { continue; } GeneratePowerlineLayout.PathNode pathNode = new GeneratePowerlineLayout.PathNode() { monument = monument, node = node }; if (!count) { pathNodes1.Add(pathNode); } else { pathNodes.Add(pathNode); } } } while (pathNodes1.Count != 0) { points1.Clear(); points2.Clear(); points1.AddRange( from x in pathNodes select x.node.point); points1.AddRange(points); points2.AddRange( from x in pathNodes1 select x.node.point); PathFinder.Node node1 = pathFinder.FindPathUndirected(points1, points2, 100000); if (node1 != null) { GeneratePowerlineLayout.PathSegment pathSegment = new GeneratePowerlineLayout.PathSegment(); for (PathFinder.Node k = node1; k != null; k = k.next) { if (k == node1) { pathSegment.start = k; } if (k.next == null) { pathSegment.end = k; } } pathSegments.Add(pathSegment); GeneratePowerlineLayout.PathNode pathNode1 = pathNodes1.Find((GeneratePowerlineLayout.PathNode x) => { if (x.node.point == pathSegment.start.point) { return(true); } return(x.node.point == pathSegment.end.point); }); pathNodes.AddRange( from x in pathNodes1 where x.monument == pathNode1.monument select x); pathNodes1.RemoveAll((GeneratePowerlineLayout.PathNode x) => x.monument == pathNode1.monument); int num4 = 1; for (PathFinder.Node l = node1; l != null; l = l.next) { if (num4 % 8 == 0) { points.Add(l.point); } num4++; } } else { GeneratePowerlineLayout.PathNode item = pathNodes1[0]; pathNodes.AddRange( from x in pathNodes1 where x.monument == item.monument select x); pathNodes1.RemoveAll((GeneratePowerlineLayout.PathNode x) => x.monument == item.monument); } } List <Vector3> vector3s = new List <Vector3>(); foreach (GeneratePowerlineLayout.PathSegment pathSegment1 in pathSegments) { for (PathFinder.Node m = pathSegment1.start; m != null; m = m.next) { float single3 = ((float)m.point.x + 0.5f) / (float)num; float single4 = ((float)m.point.y + 0.5f) / (float)num; float height01 = heightMap.GetHeight01(single3, single4); vector3s.Add(TerrainMeta.Denormalize(new Vector3(single3, height01, single4))); } if (vector3s.Count == 0) { continue; } if (vector3s.Count >= 8) { PathList pathList = new PathList(string.Concat("Powerline ", pathLists.Count), vector3s.ToArray()) { Start = true, End = true }; pathLists.Add(pathList); } vector3s.Clear(); } TerrainMeta.Path.Powerlines.AddRange(pathLists); }