void MoveAndAttack() { if (_inputListener.selectedUnits.Contains(this)) { if (state != ActorState.dead) // 안죽은 캐릭터만 { if (Input.GetMouseButtonUp(1)) { state = ActorState.move; screenPoint = Camera.main.WorldToScreenPoint(transform.position); Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z); curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint); aStarTarget.transform.position = curPosition; pathNode = aStarPathfinding.FindPath(transform.position, curPosition); //찾은 길 노드배열 } if (Input.GetKeyUp(KeyCode.S)) { state = ActorState.idle; } if (Input.GetKeyUp(KeyCode.A)) { StartCoroutine(Attack()); } } } }
void move() { //new position is closer to the first step on the rout to the player //so find this step Vector3 stepOne = pf.WorldPointFromNode(pf.FindPath(transform.position, player.transform.position)[0]); stepOne.z = 0; //dir to target Vector3 towardsPlayer = (stepOne - transform.position).normalized; rb.velocity = (towardsPlayer * speed); }
/// <summary> /// 寻路方法 /// </summary> /// <param name="e">寻路终点</param> public void FindPath(Point e) { Debug.Log("sssss"); if (pathFinding == true) { pathTweener.Kill(); //关闭寻路动画 } Point s = new Point((int)player.transform.position.x, (int)player.transform.position.y); List <Point> pathList = new List <Point>(); if (AStarPathfinding.FindPath(s, e, pathList) == false) { //ani.SetTrigger("Why"); //AudioManager.Instance.PlayClip(AudioManager.Instance.why); return; } ResetTarget(); pathFinding = true; //AudioManager.Instance.PlayClip(AudioManager.Instance.move); //ani.SetBool("Idle", !pathFinding); pathTweener = player.transform.DOPath(pathList.ToVector3Array(), pathList.Count * 0.1f); //走动效果 0.1秒执行一次动画 pathTweener.SetEase(Ease.Linear); //设置运动曲线(线性) pathTweener.onComplete += () => { //动画完成后回调方法 pathFinding = false; // ani.SetBool("Idle", !pathFinding); }; pathTweener.onKill += () => { //关闭动画回调 pathFinding = false; //ani.SetBool("Idle", !pathFinding); }; }
public override int DoLogic() { float trueSpeed = btree.btRuntimeBlackboard.blackboard["TrueSpeed"]; if (hungerManager.closerFood == null || path != null && path.Count == 0) { path = null; btree.btRuntimeParams.boolParams["WanderingEnabled"] = true; return((int)Result.FAILURE); } // Move towards the closest food in the view field if is reachable bool targetMoved = false; if (path != null) { Tile closerFoodTile = ground.TileFromWorldPoint(hungerManager.closerFood.transform.position); if (closerFoodTile != path[path.Count - 1]) { targetMoved = true; } } if (path == null || targetFood != hungerManager.closerFood || targetMoved) { // Find a path to the closer food and disable wandering behaviour targetFood = hungerManager.closerFood; Vector3 closerFoodPos = targetFood.transform.position; path = aStar.FindPath(go.transform.position, closerFoodPos); currentIndex = 0; if (path.Count <= 0) { // Already reached destination return((int)Result.SUCCESS); } currentTile = path[currentIndex]; btree.btRuntimeParams.boolParams["WanderingEnabled"] = false; } else { // Actual movement following the path found if (go.transform.position == currentTile.tilePosition) { if (currentTile == path[path.Count - 1]) { // Destination reached path = null; return((int)Result.SUCCESS); } else { currentIndex++; currentTile = path[currentIndex]; } } go.transform.position = Vector3.MoveTowards(go.transform.position, currentTile.tilePosition, trueSpeed * 1.65f * Time.deltaTime); } // Keep moving return((int)Result.FAILURE); }
// Update is called once per frame void Update() { _path = _pathfinding.FindPath(gameObject.transform.position, Target.transform.position); if (_path != null && !GetComponent <AIController>().enabled) { GetComponent <AIController>().enabled = true; } }
public void WaypointPathfinding() { var waypointData = new WaypointData(); var waypoint = new Waypoint[32]; for (int i = 0; i < waypoint.Length; ++i) { waypoint[i] = new Waypoint() { link = new List <int>(4), position = new Vector2(0, i), }; } waypoint[0].link.Add(1); waypoint[0].link.Add(2); waypoint[1].link.Add(6); waypoint[2].link.Add(6); waypoint[2].link.Add(3); waypoint[3].link.Add(4); waypoint[4].link.Add(5); waypoint[6].link.Add(7); waypoint[7].link.Add(8); waypoint[7].link.Add(9); waypointData.waypoint = waypoint; waypointData.MakeBidirectional(); var graph = new WaypointGraph(waypointData); var astar = new AStarPathfinding(); astar.FindPath(graph, 0, 9); CheckPath(astar.FormattedPath(), "path:9-7-6-2-0"); astar.FindPath(graph, 5, 8); CheckPath(astar.FormattedPath(), "path:8-7-6-2-3-4-5"); astar.FindPath(graph, 5, 31); CheckPath(astar.FormattedPath(), "path:31-x-9-7-6-2-3-4-5"); astar.FindPath(graph, 0, -1); CheckPath(astar.FormattedPath(9), "path:9-7-6-2-0"); CheckPath(astar.FormattedPath(6), "path:6-2-0"); CheckPath(astar.FormattedPath(4), "path:4-3-2-0"); CheckPath(astar.FormattedPath(11), "path:11-x-9-7-6-2-0"); }
/// <summary> /// Executes Pathfinding Upon Start being True. /// </summary> void Update() { // Start Button Pressed if (startPathfinding) { // Create a new Stopwatch Stopwatch newWatch = new Stopwatch(); // Start Watch newWatch.Start(); // Start Button no longer preseed startPathfinding = false; // Create Pathfinding Object AStarPathfinding path = new AStarPathfinding(); // Get Start and Target Nodes and Assign Materials Node startNode = GetNode(startingNodePos); Node targetNode = GetNode(targetNodePos); startNode.WorldObject.GetComponentInChildren <MeshRenderer>().material = matStart; targetNode.WorldObject.GetComponentInChildren <MeshRenderer>().material = matTarget; // Setup Unwalkable Nodes if (unwalkableNodes != null) { foreach (Vector3 node in unwalkableNodes) { grid[(int)node.x, (int)node.y, (int)node.z].Walkable = false; grid[(int)node.x, (int)node.y, (int)node.z].WorldObject.GetComponentInChildren <MeshRenderer>().material = matUnWalkable; } } // Assign Start and Target to Pathfinding System path.StartNode = startNode; path.TargetNode = targetNode; // Find Path List <Node> p = path.FindPath(); // Assign Path Node Materials for (int i = 0; i < p.Count - 1; ++i) { p[i].WorldObject.GetComponentInChildren <MeshRenderer>().material = matPath; } // Print and Stop Elapsed Time UnityEngine.Debug.Log("Path found in " + newWatch.ElapsedMilliseconds.ToString() + "ms."); newWatch.Stop(); } }
public Node PathFindNodes(Vector2 MobPos, Vector2 PlayerPos) { //Création de la liste de noeuds du a* script afin de se diriger vers le joueur en évitant les colliders PathNodes = pathfinder.FindPath(MobPos, PlayerPos); try { return(PathNodes[0]); //Retourne la position la plus proche afin que le mob s'y dirige } //Exception quand le joueur est collé au monstre, retourne la position du monstre pour qu'il ne bouge plus catch { return(new Node(false, astargrid.NodeFromWorldPoint(this.transform.position).posX, astargrid.NodeFromWorldPoint(this.transform.position).posY)); } }
/// Check to see if the target is in range of enemy or not bool TargetFound() { RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.right, 5f); if (hit.collider) { if (hit.collider.gameObject.CompareTag("Player")) { targetFound = true; targetLastPos = target.position; aStar = new AStarPathfinding(walkable.walkAbleArea); aStarPath = aStar.FindPath(new Vector2Int((int)transform.position.x + ASTAR_PATH_OFFSET, (int)transform.position.y + ASTAR_PATH_OFFSET), new Vector2Int((int)target.position.x + ASTAR_PATH_OFFSET, (int)target.position.y + ASTAR_PATH_OFFSET)); return(true); } } return(false); }
// Update is called once per frame void Update() { if (!moving) { animator.SetBool("moving", false); return; } if (Time.time >= nextTime) { findPath = aStarPathfinding.FindPath(transform.position, player.transform.position); nextTime += Random.Range(0.5f, 1.5f); } // Nowhere to path-find. if (findPath.Count == 0) { return; } // Find the next cell to move into. var worldPoint = aStarPathfinding.WorldPointFromNode(findPath[0]); var target = worldPoint - transform.position; // If the next cell is too close and there are more cells, move towards the second-closest cell. if (target.magnitude < 1 && findPath.Count > 1) { worldPoint = aStarPathfinding.WorldPointFromNode(findPath[1]); target = worldPoint - transform.position; // Remove the now-too-close cell from the list. findPath.RemoveAt(0); } // Rotate towards next cell. transform.up = Vector3.Lerp(transform.up, target, 0.1f); // Move towards next cell. var movement = Vector3.ClampMagnitude(target, 1); animator.SetBool("moving", target.magnitude > 1); transform.position += movement * speed * Time.deltaTime; }
void FollowWithAstar() { aStar = new AStarPathfinding(walkable.walkAbleArea); aStarPath = aStar.FindPath(new Vector2Int((int)transform.position.x + ASTAR_PATH_OFFSET, (int)transform.position.y + ASTAR_PATH_OFFSET), new Vector2Int((int)target.position.x + ASTAR_PATH_OFFSET, (int)target.position.y + ASTAR_PATH_OFFSET)); //DrawLine(aStarPath); if (aStarPath.Count > 0) { Vector2 newPath = new Vector2(aStarPath[1].position.x - aStarPath[0].position.x, 0).normalized; rb.velocity = newPath * speed * Time.fixedDeltaTime + new Vector2(0, rb.velocity.y); if (aStarPath[1].position.y > aStarPath[0].position.y) { Jump(); } } }
public Vector3[] FindPath(Vector3 source, Vector3 destination) { Point3D sourceCell = GetClosestFreePoint(source); Point3D destinationCell = GetClosestFreePoint(destination); AStarPathfinding aStarPathfinding = new AStarPathfinding(); List <Point3D> path = aStarPathfinding.FindPath(environmentMap, sourceCell, destinationCell); if (path == null) { return(null); } Vector3[] result = new Vector3[path.Count]; for (int i = 0; i < result.Length; i++) { result[i] = ConvertCellToPosition(path[i]); } return(result); }
void Update() { if (startCell && endCell && startCell != endCell && isUpdatePath) { StartCoroutine(_pathfinder.FindPath(GetGraphEdges(Cells), startCell, endCell, ((p) => { path = p; if (path != null && path.Count > 0) { path.ForEach(c => { if (c != startCell && c != endCell) { c.MarkAsPath(); } }); } StartCoroutine(DrawPath()); }))); isUpdatePath = false; } }
public override int DoLogic() { bool wanderingEnabled = btree.btRuntimeParams.boolParams["WanderingEnabled"]; if (wanderingEnabled) { btree.btRuntimeBlackboard.blackboard["TrueSpeed"] = wanderEditor.wanderSpeed; float trueSpeed = btree.btRuntimeBlackboard.blackboard["TrueSpeed"]; if (targetTile != null && go.transform.position != targetTile.tilePosition) { if (currentTile == null) { Debug.LogError("currentTile is NULL!!"); } // Keep moving towards target tile if (go.transform.position == currentTile.tilePosition) { currentIndex++; currentTile = path[currentIndex]; } go.transform.position = Vector3.MoveTowards(go.transform.position, currentTile.tilePosition, trueSpeed * Time.deltaTime); } else { // Select another target tile and find a path to reach it Tile[,] grid = ground.tiles; int randomX = Random.Range(0, ground.columns); int randomY = Random.Range(0, ground.rows); targetTile = grid[randomX, randomY]; if (recentTilesQueue.Contains(targetTile) || targetTile.tileType == TileType.Type.ROCK || targetTile.tileType == TileType.Type.HOME) { // The tile selected isn't eligible targetTile = null; return((int)Result.FAILURE); } // A target tile has been found path = aStar.FindPath(go.transform.position, targetTile.tilePosition); if (path.Count == 0) { // Already reached destination targetTile = null; return((int)Result.SUCCESS); } currentIndex = 0; currentTile = path[currentIndex]; recentTilesQueue.Enqueue(targetTile); if (recentTilesQueue.Count > 4) { recentTilesQueue.Dequeue(); } } } else { // Wandering was disabled then reset target tile to recalculate a new path targetTile = null; } return((int)Result.SUCCESS); }
public override int DoLogic() { bool escaping = btree.btRuntimeParams.boolParams["Escaping"]; bool hidden = btree.btRuntimeParams.boolParams["Hidden"]; float trueSpeed = btree.btRuntimeBlackboard.blackboard["TrueSpeed"]; float threatDist = btree.btRuntimeBlackboard.blackboard["ThreatDistance"]; if (escaping) { return((int)Result.FAILURE); } if (hidden) { timePassed += Time.deltaTime; timePassed = Mathf.Clamp(timePassed, 0, hidingTime); } // Detect all hideouts in range Collider2D[] hideouts = Physics2D.OverlapCircleAll(go.transform.position, hideEditor.hideRange, LayerMask.GetMask("Hideout")); if (hideouts.Length > 0 && threatDist > hideEditor.hideRange / 2) { // There is at least one hideout in range then find the closest one float minDist = Vector3.Distance(go.transform.position, hideouts[0].transform.position); hideoutPos = Vector3.negativeInfinity; foreach (Collider2D hideout in hideouts) { float dist = Vector3.Distance(go.transform.position, hideout.transform.position); if (dist <= minDist) { minDist = dist; hideoutPos = hideout.transform.position; } } if (hideoutPos != Vector3.negativeInfinity) { // We don't want to eat in this situation hungerManager.closerFood = null; btree.btRuntimeParams.boolParams["GoingSafe"] = true; if (path != null && path.Count <= 0) { // Already hiding in a hideout path = null; if (timePassed == hidingTime) { btree.btRuntimeParams.boolParams["GoingSafe"] = false; timePassed = 0; } btree.btRuntimeParams.boolParams["Hidden"] = true; if (go.transform.position != hideoutPos) { go.transform.position = Vector3.MoveTowards(go.transform.position, hideoutPos, trueSpeed * Time.deltaTime); } return((int)Result.SUCCESS); } // Closest hideout found if (path == null) { // Find a path to reach the hideout found path = aStar.FindPath(go.transform.position, hideoutPos); currentIndex = 0; if (path.Count <= 0) { // Already reached destination if (timePassed == hidingTime) { btree.btRuntimeParams.boolParams["GoingSafe"] = false; timePassed = 0; } btree.btRuntimeParams.boolParams["Hidden"] = true; return((int)Result.SUCCESS); } currentTile = path[currentIndex]; } else { // Move towards the hideout if (go.transform.position == currentTile.tilePosition) { if (currentTile == path[path.Count - 1]) { // We have reached the hideout Debug.Log(go + " is hiding!"); path = null; if (timePassed == hidingTime) { btree.btRuntimeParams.boolParams["GoingSafe"] = false; timePassed = 0; } btree.btRuntimeParams.boolParams["Hidden"] = true; } else { currentIndex++; currentTile = path[currentIndex]; } } go.transform.position = Vector3.MoveTowards(go.transform.position, currentTile.tilePosition, trueSpeed * 1.8f * Time.deltaTime); } return((int)Result.SUCCESS); } } // No hideout found return((int)Result.FAILURE); }
public override int DoLogic() { // Escape in the opposite direction of the threat incoming float trueSpeed = btree.btRuntimeBlackboard.blackboard["TrueSpeed"]; float threatDist = btree.btRuntimeBlackboard.blackboard["ThreatDistance"]; // Check in a range equals to the threat distance to get the direction Collider2D threat = Physics2D.OverlapCircle(go.transform.position, threatDist, LayerMask.GetMask("Dinosaur")); Vector3 threatDir = (threat.transform.position - go.transform.position).normalized; Vector3 threatDirRotateLeft = (Quaternion.Euler(0, 0, 115) * -threatDir).normalized; Vector3 threatDirRotateRight = (Quaternion.Euler(0, 0, -115) * -threatDir).normalized; Debug.DrawRay(go.transform.position, -threatDir); Debug.DrawRay(go.transform.position, threatDir); Debug.DrawRay(go.transform.position, threatDirRotateLeft, Color.yellow); Debug.DrawRay(go.transform.position, threatDirRotateRight, Color.green); if (targetTile != null) { // Keep moving to the target tile if (go.transform.position == currentTile.tilePosition) { if (currentTile == path[path.Count - 1]) { // We have reached the safe place path = null; targetTile = null; btree.btRuntimeParams.boolParams["GoingSafe"] = false; btree.btRuntimeParams.boolParams["Escaping"] = false; } else { currentIndex++; currentTile = path[currentIndex]; } } go.transform.position = Vector3.MoveTowards(go.transform.position, currentTile.tilePosition, trueSpeed * 1.8f * Time.deltaTime); } else { // Select a random tile at the opposite direction Tile[,] grid = ground.tiles; Tile myTile = ground.TileFromWorldPoint(go.transform.position); List <Tile> selectedTiles = new List <Tile>(); int neighbourX; int neighbourY; for (int x = -2; x <= 2; x++) { for (int y = -2; y <= 2; y++) { neighbourX = myTile.xPos + x; neighbourY = myTile.yPos + y; if (x == 0 && y == 0 || neighbourX < 0 || neighbourX >= ground.columns || neighbourY < 0 || neighbourY >= ground.rows) { // Avoid our tile and those one that go outside the grid continue; } if (Random.value >= 0.5 && selectedTiles.Count < 5) { selectedTiles.Add(grid[neighbourX, neighbourY]); } } if (selectedTiles.Count == 5) { break; } } while (targetTile == null && selectedTiles.Count > 0) { targetTile = selectedTiles[selectedTiles.Count - 1]; if (targetTile.tileType != TileType.Type.ROCK && targetTile.tileType != TileType.Type.HOME) { Vector3 tileDir = (targetTile.tilePosition - go.transform.position).normalized; float dotThreatTile = Vector3.Dot(-threatDir, tileDir); if (dotThreatTile > Mathf.Cos(Mathf.Deg2Rad * 115)) { // Good tile for escaping break; } } // The tile selected isn't eligible targetTile = null; selectedTiles.RemoveAt(selectedTiles.Count - 1); } if (targetTile != null) { Debug.DrawLine(go.transform.position, targetTile.tilePosition, Color.cyan); btree.btRuntimeParams.boolParams["GoingSafe"] = true; btree.btRuntimeParams.boolParams["Escaping"] = true; Debug.Log(go.name.ToUpper() + " is escaping!"); path = aStar.FindPath(go.transform.position, targetTile.tilePosition); currentIndex = 0; currentTile = path[currentIndex]; } } // We return always success because we want to save our life return((int)Result.SUCCESS); }
void UpdatePath(Vector3 target) { pathfinding.FindPath(transform.position, target); path = pathfinding.GetPath(); }
// Update is called once per frame void Update() { n = a.FindPath(transform.position, target.position); Debug.Log(n); }