public override Type Tick() { float dist = Vector2.Distance(character.floorPosition, player.floorPosition); //if too far, chase if (dist > Guard.ATTACK_RANGE) { Reset(); return(typeof(ChaseState)); } //attack, dash, wait, return to chase state if (!didAttack) { AttackCheck(); } else if (dashTimer < DASH_TIME) { dashTimer += Time.deltaTime; rb.velocity = PathFinding.GetVelocity(character.floorPosition, player.floorPosition, DASH_SPEED); } else if (recoveryTimer < RECOVERY_TIME) { rb.velocity = Vector2.zero; recoveryTimer += Time.deltaTime; } else { Reset(); return(typeof(ChaseState)); } return(null); }
public void play() { playing = true; currentTile = PathFinding.getTileAt(transform.position); state = 0; playMovement(); }
void Start () { rank = UnitRank.Peasant; CurrentTile = transform.GetComponentInParent<Tile>(); // This will find the village associated with this peasant, which will be the variable home. PathFind = transform.gameObject.GetComponentInParent<PathFinding>(); List<Tile> tiles = PathFind.GetTiles(CurrentTile); foreach (Tile t in tiles) { if (t.HasVillage) { Home = t.Village.transform.GetComponent<Village>(); } } _neutral = false; _home = false; _enemy = false; _water = false; CurrentTile.HasPeasant = true; Glow = transform.FindChild("Glow").gameObject; // Box = transform.FindChild("IsBusy").gameObject; Box.SetActive(false); }
void Start() { GameObject circleObj = Instantiate <GameObject> (observationCirclePrefab, transform.position, Quaternion.identity); observationCircle = circleObj.GetComponent <ObservationCircle>(); observationCircle.SetOwner(this); drawnPath = new List <GridNode> (); subPaths = new Dictionary <int, Vector3[]> (); line = GetComponent <LineRenderer> (); line.enabled = false; animator = GetComponent <Animator> (); circleCollider = GetComponent <CircleCollider2D> (); // Throwable has grabbed the first two particle system children // shockparticles is next, followed by buttonGlow ParticleSystem[] allParticles = GetComponentsInChildren <ParticleSystem> (); shockParticles = allParticles [2]; buttonGlow = allParticles [3]; // InfoCanvas initialization emotionButton = GetComponentInChildren <Button>(); emotionButtonRect = emotionButton.GetComponent <RectTransform> (); currentSpeech = GetComponentInChildren <Image> (); currentSpeech.enabled = false; Text[] robotNamePlate = GetComponentsInChildren <Text> (); name = RobotNames.Instance.TryGetSurvivorName(); robotNamePlate[0].text = name; robotNamePlate[1].text = name; sqrTargetSlowdownDistance = slowdownDistance * slowdownDistance; grid = GameObject.FindObjectOfType <Grid> (); pathFinder = GameObject.FindObjectOfType <PathFinding> (); spawnTime = Time.time; }
public static PathFinding getInstance() { if (instance == null) instance = new PathFinding (); return instance; }
/*================================================================== * MOVES * ================================================================*/ public List <Point> GetMoves(CombatMap map) { int energyMove = energy > 0 ? 1 : 0; int baseRange = move + bonusMove; int energyRange = baseRange + energyMove; // Get valid moves List <Point> moves = PathFinding.GetTiles(map, moveType, position, energyRange, 1); List <Point> result = new List <Point>(); foreach (Point p in moves) { if (map.unitManager.CanEnter(p)) { result.Add(p); } } // Check energy tiles for (int i = 0; i < result.Count; i++) { Point p = result[i]; int distance = PathFinding.GetDistance(moveType, position, p); p.z = (byte)(distance > baseRange ? 1 : 0); result[i] = p; } return(result); }
public void EscapeFromTarget() { PathFinding src_path = new PathFinding(); src_path.OnStreet(Entity); PathFinding from_path = new PathFinding(); from_path.OnStreet(Target); Road Road = null; for (int src = 0; src < src_path.Roads.Count; src++) { for (int from = 0; from < from_path.Roads.Count; from++) { if (src_path.Roads[src].X == from_path.Roads[from].X && src_path.Roads[src].Y == from_path.Roads[from].Y && src_path.Roads[src].Z == from_path.Roads[from].Z) { if (Road == null || Road.Street.Length < src_path.Roads[src].Street.Length) { Road = src_path.Roads[src]; } } } } if (Road != null) { Entity.Move = new MoveJSON(); Entity.Move.Body = new BodyJSON(new ImageJSON[] { new ImageJSON("Mobile_Move", 1, 1) }, true, true, 750, -1); Entity.Move.Street = Road.Street; //Entity.Move.Step = 0; Entity.MoveStart(); } }
public override Type Tick() { //check if too low to maintain pursuit if (character.health / character.maxHealth <= FLEE_HEALTH) { return(typeof(FleeState)); } rb.velocity = Vector2.zero; float dist = Vector2.Distance(character.floorPosition, player.floorPosition); //check if still in aggro range if (dist > Guard.AGGRO_LEASH) { return(typeof(IdleState)); } //check if in range of attacking if (dist <= Guard.ATTACK_RANGE) { return(typeof(AttackState)); } //chase that mofo rb.velocity = PathFinding.GetVelocity(character.floorPosition, player.floorPosition, character.speed); return(null); }
/// <summary> /// Gets the snapped geometry from the map matcher's current state (potentially after the map matcher breaks) /// </summary> /// <param name="matcher"></param> /// <param name="cleanShape"></param> /// <param name="startIndex"></param> /// <param name="breakIndex"></param> /// <returns></returns> private List <Coord> GetSnappedSection(OsmMapMatcher matcher, List <Coord> cleanShape, int startIndex, int breakIndex) { var sequenceSoFar = matcher.State.GetMostLikelySequence(); var connectedSequence = PathFinding.DijstraConnectUpSequence(sequenceSoFar, matcher.Graph); return(TrimRoadSequence(connectedSequence.Select(st => st.Geometry).ToList(), cleanShape[startIndex], cleanShape[breakIndex])); }
private void Update() { int i = 0; //if there are current jobs in the list then check if they're done and remove while (i < currentJobs.Count) { if (currentJobs[i].jobDone) { currentJobs.RemoveAt(i); } else { i++; } } //Check if there is jobs to do in list and the max number of threads arent all currently in use then create thread and do job if (todoJobs.Count > 0 && currentJobs.Count < MaxThreads) { PathThread job = todoJobs[0]; todoJobs.RemoveAt(0); currentJobs.Add(job); //Start a new thread ThreadStart newThread = delegate { job.path = PathFinding.CalculatePath(job.startPos, job.targetPos, out string output); job.jobDone = true; }; Thread jobThread = new Thread(newThread); jobThread.Start(); } }
// Listen for messages from other NPCs protected void SawPlayer(Vector3 pos) { if (currentNode == null) { return; } if (currentState == State.PATROL_LEVEL || currentState == State.MAP_LEVEL) { playerPos = pos; gotPlayerPos = true; // Try and generate a path to the player List <PathNode> newPath = PathFinding.FindPath(currentNode, cellGrid.GetPathfindingNode(cellGrid.GetCellAtPos(playerPos))); // If we succeeded in generating a path & we aren't currently chasing the player // Switch to going to find the player if (newPath.Count != 0) { currentPath = newPath; SwitchState(State.LOOK_FOR_PLAYER); } } }
private void Awake() { pathFinding = new PathFinding(); wayPoints = new List <Tile>(); viewedTiles = new HashSet <Tile>(); gotTile = false; }
/*public GameManager (int width = 100, int height = 100) { * totalSize = new IntVector2(width, height); * CrearMapa(); * * inventario = new Inventario(int.MaxValue); * inventario.SetInterface((IEquipo) this); * }*/ void Awake() { builds = new Dictionary <ESTRUCTURA, List <Estructura> >(); characters = new List <Personaje>(); farm = GetComponent <Agricultura>(); build = GetComponent <Construccion>(); management = GetComponent <ManagementManager>(); time = GetComponent <TimeManager>(); craft = GetComponent <Artesania>(); info = GetComponent <Informacion>(); characterController = GetComponent <CharacterInterfaceController>(); path = new PathFinding(this); actions = new ActionManager(this); lightManager = FindObjectOfType <LightManager>(); resourceController = FindObjectOfType <ResourceController>(); interfaz = FindObjectOfType <UIManager>(); //TODO: //Poner esto en el Start cuando no haya estructuras pregeneradas. tiles = new Dictionary <Node, SpriteRenderer>(); CrearMapa(); inventario = new Inventario(int.MaxValue, this); inventario.SetInterface((IEquipo)this); }
public static bool SelectUnit(Hex hex) { if (hex == null || (hex.unit == null && selectedUnit == null)) { return(false); } if (selectedUnit != null) { if (selectedUnit.movableHexes.ContainsKey(hex)) { MoveUnit(hex); return(false); } else { //check if hex is in the attack range if (selectedUnit.attackableHexes.Contains(hex)) { selectedUnit.Attack(hex.unit); //attack } } } selectedUnit = hex.unit; ShowTransportButtons?.Invoke(selectedUnit); selectedUnit.movableHexes = PathFinding.GetMovableHexes(hex, selectedUnit.moves, selectedUnit.type); PathFinding.GetAttackableHexes(selectedUnit); return(true); }
// Compute and activate all possible actions // by default (null) caseDepart will be character's current cell public void computePossibleActions(CaseBehavior caseDepart = null) { if (caseDepart == null) { caseDepart = caseActuelle.GetComponent <CaseBehavior>(); } int row = caseDepart.row; int column = caseDepart.column; pathfinder = new PathFinding(gManager, row, column, this); if (!surLaRegletteAdverse(caseDepart)) // the movement must stop once on the opponent zone. { caseDepart.selectionnePourDeplacement = true; // Changer le SortingLayer +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ pathfinder.SearchPossibleActions(); activatePossibleActions(); caseDepart.cibleAssociated.GetComponent <Collider>().enabled = false; } }
// Update is called once per frame private void Updating() { if (player) { if (Vector3.Distance(player.transform.position, transform.position) > 5) { Vector3 toPosition = player.transform.position; Vector3 direction = toPosition - transform.position; Vector3Int ennemiPlayer = new Vector3Int((int)transform.position.x, (int)transform.position.y, (int)transform.position.z); float dist = Vector2Int.Distance(new Vector2Int(ennemiPlayer.x, ennemiPlayer.y), new Vector2Int((int)toPosition.x, (int)toPosition.y)); if (dist < _aggroRange && dist > 1) { _offset = ennemiPlayer - new Vector3Int(1, 1, 0) * _aggroRange; int[,] map = TransformTilemap(ennemiPlayer, tlm); Vector3 posPlayer = player.transform.position - _offset; Vector2 pos2D = posPlayer; map = AddCornerPlayer(pos2D, map); Vector2Int plz = new Vector2Int((int)pos2D.x, (int)pos2D.y); path = PathFinding.FindPath(new Vector2Int(_aggroRange, _aggroRange), plz, map); } } } }
//subscribed to OnStateChanged event private void GetPath(BaseState state) { if (state is FleeState && character is TownspersonClass) { path = PathFinding.AStarJump(character.floorPosition, ((TownspersonClass)character).building.entrance.transform.position, character.nodeMap, character.nodeID); } }
public bool Move(Cell targetCell, bool animate, int distance) { if (animate) { List <Cell> path = PathFinding.FindPath(MapInfos, CurrentCell, targetCell); if (path != null) { Movement.StartMovement(path, CurrentCell); ProjectionManager.SelectPath(path); } } else { transform.position = targetCell.GetVector3Position(); } if (CurrentCell != null) { CurrentCell.IsTaken = null; } CurrentCell = targetCell; CurrentCell.IsTaken = this; if (distance > 0) { AttributesSheet.AddCostAttribute(new Attribute(AttributeType.MovementPoint, -distance, PropertyType.Value, 1)); CombatUIManager.UpdateMovementPoint(AttributesSheet.GetAttribute(AttributeType.MovementPoint)); } return(true); }
// Update is called once per frame void Update() { if (Input.GetButtonDown("Fire1")) { if (!EventSystem.current.IsPointerOverGameObject()) { Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); GameObject g = PathFinding.getTileAt(mousePos); if (g != null) { path = PathFinding.aStarPathFinding(PathFinding.getTileAt(transform.position), g); GameObject currentTile = PathFinding.getTileAt(transform.position); if (path[0].transform.position != currentTile.transform.position) //make sure the palyer cannot diagonally { float tileDist = PathFinding.IsometricDistance(currentTile.transform.position, path[0].transform.position); //distance between current tile and next tile float playerToNextTileDist = PathFinding.IsometricDistance(transform.position, path[0].transform.position); //distance between player and next tile if (tileDist < playerToNextTileDist) //ensures that the player does not need to go back to a tile if it is not on it's way { path.Insert(0, currentTile); } } transform.GetComponent <playerOverall>().updatePath(path); } } } }
void Awake() { pathFinder = GetComponent <PathFinding> (); EnemyPlayer.EnemyHealth.OnDeath += OnDeath; EnemyPlayer.OnTargetSelected += OnTargetSelected; }
private IEnumerator StaggerdPathThroughMaze(Node lastNode) { foreach (Node waypoint in Spawner.waypoints) { List <Node> pathingPoints = PathFinding.AStar(lastNode, waypoint); yield return(new WaitForEndOfFrame()); foreach (Node pathingPoint in pathingPoints) { moveQue.Add(pathingPoint); } lastNode = moveQue[moveQue.Count - 1]; yield return(new WaitForSeconds(.05F)); } yield return(new WaitForSeconds(.1F)); List <Node> toEndPathPoints = PathFinding.AStar(lastNode, endNode); yield return(new WaitForEndOfFrame()); foreach (Node pathingPoint in toEndPathPoints) { moveQue.Add(pathingPoint); } }
void CreateNavMap() { /* * List<NavMap> navList = new List<NavMap> (); * foreach (GameObject map in finalRegions) { * NavMap nav = map.AddComponent<NavMap> (); * nav.mapSize = new Vector2 (roomSize - 1, roomSize - 1); * nav.nodeRadius = .5f; * nav.CreateGrid (); * map.GetComponent<MapGenerator> ().self.navMap = nav; * navList.Add (nav); * } */ GameObject navigation = new GameObject(); navigation.name = "navigation"; navigation.transform.position = new Vector3(0, 0, (regionHeight / 2) * roomSize); NavMap nav = navigation.AddComponent <NavMap> (); nav.mapSize = new Vector2(regionWidth * roomSize, regionHeight * roomSize); nav.nodeRadius = .5f; nav.CreateGrid(); PathFinding finder = navigation.AddComponent <PathFinding> (); PathManager manager = navigation.AddComponent <PathManager> (); finder.requestManager = manager; }
public static void MoveUnit(Hex moveToHex) { selectedUnit.moveToHex = moveToHex; if (selectedUnit.hex.unit == selectedUnit) { selectedUnit.hex.unit = null; } else { selectedUnit.hex.unit.UnBoardTransport(selectedUnit); } if (moveToHex.unit == null) { moveToHex.unit = selectedUnit; } else { moveToHex.unit.BoardTransport(selectedUnit); } PathFinding.ClearPaths(); selectedUnit.Move(true); selectedUnit = null; ShowTransportButtons?.Invoke(null); }
public override Type Tick() { rb.velocity = Vector2.zero; //if wildlife, run away from player if (character is Wildlife) { rb.velocity = new Vector2(-1f, -1f) * PathFinding.GetVelocity(character.floorPosition, player.floorPosition, character.speed * 2); } //if townie, run home else { if (path.Count > 0) { rb.velocity = PathFinding.GetVelocity(character.floorPosition, path[0], character.speed); if ((character.floorPosition - path[0]).sqrMagnitude <= PathFinding.TOLERANCE) { path.RemoveAt(0); } } else { // once path is done, switch to a different state return(typeof(RestState)); } } return(null); }
public IEnumerator Generate() { WaitForSeconds delay = new WaitForSeconds(0.01f); cells = new MazeCell[size.x, size.z]; List <MazeCell> activeCells = new List <MazeCell>(); DoFirstGenerationStep(activeCells); while (activeCells.Count > 0) { yield return(delay); DoNextGenerationStep(activeCells); } targetCoordinates = RandomCoordinates; foreach (Transform child in cells[targetCoordinates.x, targetCoordinates.z].transform) { //Debug.Log(child. Renderer rendered = child.gameObject.GetComponent <Renderer>(); if (rendered != null) { rendered.material.color = Color.red; } } tanks = new Tank[numTanks]; for (int i = 0; i < numTanks; i++) { IntVector2 coordinates = RandomCoordinates; Tank newTank = this.createTank(i, coordinates); tanks[i] = newTank; } this.pathFinding = new PathFinding(); }
public void Obstacle_2() { int sizeX = 7; int sizeY = 4; int startX = 0; int startY = 3; int endX = 6; int endY = 1; var mapInfo = new DefaultMapInfo(sizeX, sizeY); mapInfo.SetWalkable(3, 1, false); mapInfo.SetWalkable(4, 1, false); mapInfo.SetWalkable(4, 2, false); var pathfinding = new PathFinding(mapInfo); var path = new List <int>(); pathfinding.FindPath(startX, startY, endX, endY, path); string expected = "_______\n" + "___oo_E\n" + "____o#_\n" + "S####__"; string result = MapToString(sizeX, sizeY, startX, startY, endX, endY, path, mapInfo); Assert.Equal(expected, result); }
//Awake is always called before any Start functions void Awake() { //Check if instance already exists if (instance == null) { //if not, set instance to this instance = this; } else if (instance != this) { //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager. Destroy(gameObject); } // Sets this to not be destroyed when reloading scene. DontDestroyOnLoad(gameObject); // Get our component references. boardScript = GetComponent <BoardManager>(); enemyManager = GetComponent <EnemyManager>(); colonyManager = GetComponent <ColonyManager>(); cameraMan = Camera.main.GetComponent <CameraManager>(); pathfinder = GetComponent <PathFinding>(); //Call the InitGame function to initialize the first level InitGame(); }
void walkToMousePos() { if (!EventSystem.current.IsPointerOverGameObject() && !isWalking) { Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); GameObject g = PathFinding.getTileAt(mousePos); if (g != null) { Vector3 target = g.transform.position; List <GameObject> path = PathFinding.aStarPathFinding(PathFinding.getTileAt(transform.transform.position), g); if (path.Count <= currentMovementPoints) { bool canMove = GetComponent <playerOverall>().takeTile(target); if (canMove) { isWalking = true; GetComponent <playerOverall>().updatePath(path); currentMovementPoints -= path.Count; updateMovementPoints(); } } } } }
/// <summary> /// 初始化寻路 /// </summary> private void InitPathfinding() { if (m_SearchPath == null) { m_SearchPath = new PathFinding(this); } if (Application.isPlaying) { if (m_FindAttackRange == null) { m_FindAttackRange = ScriptableObject.CreateInstance <FindRange>(); } if (m_FindMoveRange == null) { m_FindMoveRange = ScriptableObject.CreateInstance <FindMoveRange>(); } if (m_FindPathDirect == null) { m_FindPathDirect = ScriptableObject.CreateInstance <FindPathDirect>(); } } if (m_CellPositionEqualityComparer == null) { m_CellPositionEqualityComparer = new CellPositionEqualityComparer(); } }
//Extends a point created void extendBranch() { Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); if (currentGameObject != null) { if (currentGameObject.transform.parent != null && currentGameObject.transform.parent.GetComponent <LineRenderer>() != null) { lineFollow(currentGameObject, mousePos, 1); } currentGameObject.transform.position = mousePos; } else { GameObject tile = PathFinding.getObjectAtMousePos(); if (tile != null) { GameObject p = tile.GetComponent <tile>().getTakenBy(); if (p != null && p.tag == "Spell") { createNewPoint(p); foreach (Transform child in currentGameObject.transform) { Destroy(child.gameObject); } currentGameObject.transform.parent = p.transform; currentGameObject.transform.localScale = new Vector3(1, 1, 1); createLineRenderer(currentGameObject, p.transform.position); currentChildren = null; } } } }
//shows possible paths to the user void drawPath() { stillDrawn = true; GameObject t = PathFinding.getTileAt(Camera.main.ScreenToWorldPoint(Input.mousePosition)); if (t != null) { GameObject currentTile = PathFinding.getTileAt(transform.position); if (currentTile != null) { foreach (GameObject tile in drawnPaths) { UiManager.changeAlpha(tile, false, 1f); } if (!EventSystem.current.IsPointerOverGameObject()) { drawnPaths = PathFinding.aStarPathFinding(currentTile, t); for (int i = 0; i < currentMovementPoints && i < drawnPaths.Count; i++) { if (i == drawnPaths.Count - 1 && drawnPaths[i].GetComponent <tile>().taken) //if the last item in path is taken then do not draw it { } else { UiManager.changeAlpha(drawnPaths[i], false, 0.5f); } } } } } }
void Start() { rank = UnitRank.Knight; //Debug.Log("Knight Start has been called"); // Get current tile position CurrentTile = transform.GetComponentInParent<Tile>(); //Debug.Log ("CurrentTile : "+CurrentTile); //this will find the village associated with this Knight, which will be the variable home. PathFind = transform.gameObject.GetComponentInParent<PathFinding>(); List<Tile> tiles = PathFind.GetTiles(CurrentTile); //Debug.Log (tiles.Count); foreach (Tile t in tiles) { if (t.HasVillage) { Home = t.Village.transform.GetComponent<Village>(); } } _neutral = false; _home = false; _enemy = false; _water = false; // TODO: Test purposes only CurrentTile.HasKnight = true; //Debug.Log(CurrentTile); Glow = transform.FindChild("Glow").gameObject; }
protected bool AttackPlayer() { // FULL SPEED AHEAD targetMovementSpeed = 1.0f; // Look for player towards the last known position // Calculate intercept vector Vector3 dir = (playerPos - transform.position).normalized; // Find nearest cell with cover from player PathNode coverNode; Vector3 coverPos; if (currentPath == null) { if (FindCover(out coverNode, out coverPos)) { // Get node position Vector3 nodePos = cellGrid.GetCellPos( cellGrid.Grid[(int)coverNode.Position.x, (int)coverNode.Position.y]); // Path find to cover (or just the farthest away node if we didn't find cover) currentPath = PathFinding.FindPath(currentNode, coverNode); // If the path length is 1 (we're already on the cell), move towards hidePos if (currentPath.Count == 1) { Move((coverPos - transform.position)); } } // If we couldn't find any cover, just run away else { Move(-dir); } } // If we can see the player, shoot at it if (CanSeeObjectOnLayer(dir, playerLayer, "Player")) { dir = Quaternion.AngleAxis(Random.Range(-0.5f, 0.5f) * LOOK_PLAYER_JITTER, Vector3.forward) * (playerPos - transform.position).normalized; TurnTowards(dir); // Shoot once we're facing the right direction if (Vector3.Angle(dir, FacingDirection) < 1.0f) { Fire(); } } // Otherwise, look for it else { SwitchState(State.LOOK_FOR_PLAYER); return(false); } return(true); }
void Awake (){ if(instance){ DestroyImmediate(gameObject); return; } instance = this; DontDestroyOnLoad(gameObject); }
void Start(){ pathfinder = GameObject.Find("GameManager/PathFinder").GetComponent<PathFinding>(); heatmanager = GameObject.Find("GameManager/PathFinder").GetComponent<HeatMapManager>(); grid = GameObject.Find("GameManager/PathFinder").GetComponent<Grid>(); hq = GameObject.Find ("T0Spawn").GetComponent<Spawn> (); selected = GameObject.Find ("T0Spawn").GetComponent<Spawn> (); buildSpawn = transform.FindChild ("BuildSpawn").gameObject; camera = Camera.main; }
// --------------------------------------------------- /** * Static initialitzation of pathfinding, but also it can be called externally to adjust * to new parameters */ public static PathFinding InitPathfinding(int rows, int cols, float xIni, float zIni, float cellWidth, float cellHeight) { int[] matrix = new int[rows * cols]; Global.MakeMatrix(false, matrix, xIni, zIni, cellWidth, cellHeight, rows, cols); // PATHFINDING PathFinding path = new PathFinding(rows, cols, cellWidth, cellHeight, xIni, zIni); path.InitAI(matrix); return (path); }
// Use this for initialization void Start () { BuyingWatchTower = false; CurrentTile = transform.parent.GetComponent<Tile>(); //set the current tile that the village is currently on PathFind = transform.gameObject.GetComponentInParent<PathFinding>(); Debug.Log (PathFind); //Debug.Log (tiles.Count); CurrentVillage = transform.gameObject.GetComponentInParent<Village>(); netView = GetComponent<NetworkView>(); }
void Start() { CurrentTile = transform.parent.GetComponent<Tile>(); //set the current tile that the village is currently on currentColor = CurrentTile.GetComponent<Renderer>().material.color; Gold = 500; Wood = 200; ThisRank = Rank.Hovel; //set beginning village to hovel Glow = transform.FindChild("Glow").gameObject; MergeVillages m = gameObject.GetComponent<MergeVillages>(); VillageTerritory = m.GetTiles(CurrentTile); netView = GetComponent<NetworkView>(); PathFind = transform.gameObject.GetComponentInParent<PathFinding>(); CannonballShotsTaken = 0; //start with no shots on village }
void Awake(){ Agents.Clear(); foreach(Transform agent in agentsSquad){ if(agent.name != "Leader"){ Agents.Add(agent.GetComponent<UnitSquad>()); agent.GetComponent<UnitSquad>().tipoUnidad = tipoEscuadra; } } if(tipoEscuadra == squadType.Humanos){ pathfinder =GameObject.Find("GameManager/PathFinder").GetComponent<PathFinding>(); pathfinder.StartFindPath(transform.position,GameObject.Find("T0Spawn").transform.position,SetPath); } int i = 0; int j = 0; print(Agents.Count); foreach(UnitSquad a in Agents){ a.GetComponent<UnitSquad>().squad = this; if(tipoEscuadra == squadType.Swarm){ if(a.startPos.z == 1000){ a.startPos = new Vector3(Random.Range(-maxRandomMovement,maxRandomMovement), Random.Range(-maxLeaderOffset/2,maxLeaderOffset/2),0); } } else if(tipoEscuadra == squadType.Humanos){ a.startPos = new Vector3((-maxLeaderOffset + (((maxLeaderOffset*2)/maxRowElements) * j)),(-maxLeaderOffset/4) * i,0); j++; if(j == maxRowElements){ i++; j = 0; } } } }
public void init(int allowBlocks=10,int forceLayer=-1,bool saveBlocks=false) { _allowBlocks = allowBlocks; _forceLayer = forceLayer; _saveBlocks = saveBlocks; _topLeft = GameObject.Find("Marker_TopLeft"); _topRight = GameObject.Find("Marker_TopRight"); _bottomLeft = GameObject.Find("Marker_BottomLeft"); _bottomRight = GameObject.Find("Marker_BottomRight"); _width = _topRight.transform.position.x - _topLeft.transform.position.x; _height = _topRight.transform.position.y - _bottomLeft.transform.position.y; PathFinder = new PathFinding(); PathFinder.Init(GetComponent<Grid>()); GameObject gz = new GameObject("Grid_Zones"); Zones = gz.transform; blocks = new Dictionary<int, Dictionary<int, bool>>(); draw(forceLayer); }
void Awake() { if (_instance == null) { _instance = this; } grid = GetComponent<Grid>(); }
public void Generate(Level level) { if( !generated ) { string levelType = level.type; int nbrRegenerations = 10; int minimumEmptyTiles = 20; List<Vector2> doorPositions = new List<Vector2>(); while( !generated ) { floors = new int[width,height]; decors = new int[width,height]; doors = new int[width,height]; for(int y=0; y<height; y++) { for(int x=0; x<width; x++) { floors[x, y] = 1; if( x == 0 || y == 0 || y == height -1 || x == width -1 ) { decors[x, y] = 1; } } } // Remove decors // top, right, bottom, left for(int n=1; n<=4; n++) { if( neighboors.ContainsKey(n) ) { Vector2 position = new Vector2(0, 0); if( n == 1 ) { position.x = Random.Range(1, width-2); position.y = height-1; } else if ( n == 2 ) { position.x = width - 1; position.y = Random.Range(1, height-2); } else if( n == 3 ) { position.x = Random.Range(1, width-2); position.y = 0; } else if( n == 4 ) { position.x = 0; position.y = Random.Range(1, height-2); } doors[ (int)position.x, (int)position.y ] = n; doorPositions.Add( position ); // Debug.Log("New Door at " + (int)position.x + "x" + (int)position.y); decors[ (int)position.x, (int)position.y ] = 0; } } switch( levelType ) { case "spreadable": RandomFillMap(); for(int i=0; i<1; i++) { SmoothMap(); } break; } // decors[2,2] = 1; // decors[2,3] = 1; // decors[3,2] = 1; // decors[3,3] = 1; // decors[4,2] = 1; // decors[4,3] = 1; // // decors[3,4] = 1; // Find all empty tiles // -------------------------------------------------------------------- int emptyTiles = 0; for(int y=0; y<height; y++) { for(int x=0; x<width; x++) { if( decors[x, y] == 0 ) { emptyTiles++; } } } // Match the minimumEmptyTiles/maximum retries or regenerate // -------------------------------------------------------------------- if( emptyTiles > minimumEmptyTiles || nbrRegenerations <= 0 ) { generated = true; } else { nbrRegenerations--; if( nbrRegenerations <= 1 ) { levelType = "empty"; // Force an empty room } } } // Find a place for all entities // ---------------------------------------------------------------------- for(int i=0; i<entities.Count; i++) { Vector2 p = GetRandomPosition(); entities[i].x = (int)p.x; entities[i].y = (int)p.y; } if( doorPositions.Count > 1 ) { PathFinding pf = new PathFinding(decors, width, height); for(int d=0; d<doorPositions.Count-1; d++) { List<Vector2> paths = pf.Find(doorPositions[d], doorPositions[d+1]); if( paths.Count > 2 ) { for(int i=0; i<paths.Count; i++) { floors[ (int)paths[i].x, (int)paths[i].y ] = 2; } } } } } }
void Start() { managerContext = this; targetFinder = GetComponent<PathFinding>(); }
void Awake() { instance = this; pathfinding = GetComponent<PathFinding>(); }
void Start() { Plan = new Queue<Command>(); team = transform.parent.GetComponent<AIPlayer> ().playerID_; airesources = transform.parent.GetComponent<AIController> (); capturedtime = airesources.alltimer; pathing = GetComponent<PathFinding>(); if (team == 0) { GetComponent<SpriteRenderer> ().sprite = lab0; position = new Vector2(9, 16); } else if (team == 1) { GetComponent<SpriteRenderer>().sprite = lab1; position = new Vector2(10, 4); } InvokeRepeating ("Execute", 2.0f, 2.0f); }
//Insert a Pathfinding node in the tree public void Insert(PathFinding.Node pfNode, QuadTreeNode node = null, int DepthLevel = 0) { if (node == null) node = Head; //Make sure Box is smaller than current quadrant. If yes, go deeper, otherwise add elements here if (DepthLevel < this.Depth) { //Process North-West Part if (node.Children[0] != null) { if (pfNode.position.X <= node.Position.X && pfNode.position.Z <= node.Position.Y) { Insert(pfNode, node.Children[0], DepthLevel + 1); } } //Process North-East Part if (node.Children[1] != null) { if (pfNode.position.X >= node.Position.X && pfNode.position.Z <= node.Position.Y) { Insert(pfNode, node.Children[1], DepthLevel + 1); } } //Process South-West Part if (node.Children[2] != null) { if (pfNode.position.X <= node.Position.X && pfNode.position.Z >= node.Position.Y) { Insert(pfNode, node.Children[2], DepthLevel + 1); } } //Process South-East Part if (node.Children[3] != null) { if (pfNode.position.X >= node.Position.X && pfNode.position.Z >= node.Position.Y) { Insert(pfNode, node.Children[3], DepthLevel + 1); } } } else { //Add box in current layer if (node.PathFindingNodes == null) node.PathFindingNodes = new List<PathFinding.Node>(); if (!node.PathFindingNodes.Contains(pfNode)) { node.PathFindingNodes.Add(pfNode); ItemCount++; } } }
protected void moveToPosition(){ //getting next position Vector3 destination; bool hit = Physics.Linecast(transform.position, goalPosition, obstacles); if(grid == null || pathing == null || basicAttackScript == null){ grid = (Grid)GameObject.FindObjectOfType (typeof(Grid)); pathing = (PathFinding)GameObject.FindObjectOfType (typeof(PathFinding)); basicAttackScript = GetComponent<BasicAttack>(); } //check if pathfinding acutally failed if (pathing.pathFindingFailed) { //reset stopMoving(); goalPosition = transform.position; pathing.pathFindingFailed = false; return; } if(basicAttackScript.canFinishAttack()){ basicAttackScript.finishAttack(); return; } if (!hit) { destination = goalPosition; arriveScript.enabled = (steeringScript.Velocity.magnitude>=speed/2)?true:false; steeringScript.setTarget (goalPosition); } // else if(Physics.Linecast(transform.position, goalPosition, obstacles)){ // animateIdle(); // return; // } else { pathing.findPath(transform.position, goalPosition); //check if pathfinding acutally failed if (pathing.pathFindingFailed) { //reset stopMoving(); goalPosition = transform.position; pathing.pathFindingFailed = false; return; } if(previousGoal == null){ previousGoal = goalPosition; } List<Vector3> path = grid.worldFromNode(grid.path); if(path == null || grid.path == null || path.Count <= 1 || grid.path.Count <= 1){ destination = transform.position; // stopMoving(); // return; } else if (path.Count > 1) { destination = path [1];//because path[0] is where you are now, and path[1] is the immediately next step arriveScript.enabled = false; } else {//this should never happen, but its for completion. I could be wrong. but I believe if the avatar is about to approach his final destination, he should have clear sight of it destination = goalPosition; arriveScript.enabled = true; } steeringScript.setTarget (destination); } if(transform.tag != typeof(Enemy).ToString() && (ai == null || !ai.enabled) && Vector3.Distance(previousGoal, goalPosition) > 2){ previousGoal = goalPosition; if(clickedPosition == null){ clickedPosition = Instantiate (clickAnimation, goalPosition, Quaternion.Euler(180,0,0)) as GameObject; } } if (steeringScript.Velocity.magnitude > 0) { alignScript.interpolatedChangeInOrientation (steeringScript.Velocity); } if(grid.nodeFromWorld(transform.position)==grid.nodeFromWorld(goalPosition)){ stopMoving(); return; } steeringScript.steeringUpdate (); animateRun(); // networking: event listener to RPC the run anim if(playerNetworkScript != null) { playerNetworkScript.onRunTriggered(); } else { print("No fighterNetworkScript nor sorcererNetworkScript attached to player."); } //Player not moving //if(destination == goalPosition) { if(steeringScript.Velocity.magnitude==0) { moving = false; animateIdle(); if(playerNetworkScript != null) { playerNetworkScript.onIdleTriggered(); } else { print("No fighterNetworkScript nor sorcererNetworkScript attached to player."); } } }
public void setPathing(PathFinding path){ this.pathing = path; }
void Awake(){ manager = this; pathFinding = GetComponent<PathFinding>(); }
void Awake() { instance = this; PathFinder = GetComponent<PathFinding>(); }
// --------------------------------------------------- /** * Will remake the whole matrix of collision */ public static void RemakePathfinding() { m_path = InitPathfinding(ROWS, COLS, X_INITIAL, Y_INITIAL, CELL_WIDTH, CELL_HEIGHT); }
public override void Update() { if (updateTimer.ElapsedMilliseconds >= 1000) { updateTimer.Restart(); double lowestDistance = 0; BotPlayer lowestDistancePlayer = null; lock (OstBot.playerList) { foreach (BotPlayer player in OstBot.playerList.Values) { if (player.isgod) continue; double currentDistance = GetDistanceBetween(player, xBlock, yBlock); if (currentDistance < lowestDistance || lowestDistance == 0) { lowestDistance = currentDistance; lowestDistancePlayer = player; } } } if (lowestDistancePlayer != null) { targetBotPlayer = lowestDistancePlayer; } } if (targetBotPlayer != null && xBlock != targetBotPlayer.x && yBlock != targetBotPlayer.y) { //pathFinding = null; pathFinding = new PathFinding(); //lagTimer.Restart(); pathToGo = pathFinding.Begin(xBlock, yBlock, targetBotPlayer.blockX, targetBotPlayer.blockY, null); //Console.WriteLine("elapsed shitlagtime " + lagTimer.ElapsedMilliseconds + "MS"); if (pathToGo != null && pathToGo.Count != 0) { Square temp; if (pathToGo.Count >= 2) temp = pathToGo.Pop(); Square next = pathToGo.Pop(); xBlock = next.x; yBlock = next.y; zombieBlock = Block.CreateBlock(0, xBlock, yBlock, 32, -1); zombieOldBlock = Block.CreateBlock(0, xOldBlock, yOldBlock, 4, -1); OstBot.room.DrawBlock(zombieBlock); OstBot.room.DrawBlock(zombieOldBlock); } if (targetBotPlayer != null) { if (!targetBotPlayer.isDead && GetDistanceBetween(targetBotPlayer, xBlock, yBlock) <= 1 && !targetBotPlayer.isgod) { targetBotPlayer.killPlayer(); OstBot.connection.Send("say", "/kill " + targetBotPlayer.name); } } } base.Update(); }
void Start () { //Inicializamos el path para evitar errores; initPos = new Vector3(0,0,100000); //Buscamos la pool para solicitar los creeps; pool = GameObject.Find ("Pool").GetComponent<Pool> (); //Iniciamos la solicitud de creeps basicos; invokeGene [0] = true; invokeGene [1] = false; Invoke("Create",1f/spawnRate); //Iniciamos la solicitud de creeps de tier; //Invoke("CreateTier",spawnRateTier); //Texto para ver el numero de creeps; textNumberCreeps = GameObject.Find ("CreepsText/Number").GetComponent<UITest> (); numberCreeps = 0; pathfinder = GameObject.Find("GameManager/PathFinder").GetComponent<PathFinding>(); geneSpeed = 0; /*************************** * SOLO PARA LAS PRUEBAS DE LA BARRA DE GENERACION*/ spritesGene [0] = transform.FindChild ("ProductionBar/Prod_0").GetComponent<SpriteRenderer> (); spritesGene [1] = transform.FindChild ("ProductionBar/Prod_1").GetComponent<SpriteRenderer> (); spritesGene [2] = transform.FindChild ("ProductionBar/Prod_2").GetComponent<SpriteRenderer> (); spritesGene [3] = transform.FindChild ("ProductionBar/Prod_3").GetComponent<SpriteRenderer> (); spritesGene [4] = transform.FindChild ("ProductionBar/Prod_4").GetComponent<SpriteRenderer> (); /*****************************/ touchManager = GameObject.Find ("GameManager/TouchManager").GetComponent<TouchManager> (); tier = 0; subType = -1; numBioPools = 0; }