Пример #1
0
 // Use this for initialization
 void Start()
 {
     pathGenerator = new AStarPath();
     path          = new List <AStarConnection>();
     test          = GameObject.FindObjectOfType <AStarTest>();
     tf            = GetComponent <Transform>();
 }
Пример #2
0
 void Start()
 {
     astarTime = gameObject.transform.FindChild("AstarTime").GetComponent<Text>();
     fringeTime = gameObject.transform.FindChild("FringeTime").GetComponent<Text>();
     a = GameObject.Find("Floor").GetComponent<AStarPath>();
     f = GameObject.Find("Floor").GetComponent<FringePath>();
 }
Пример #3
0
        // Returns bool representing if the path has been found the path itself
        private Tuple <bool, AStarPath> FindDirectPath(ITransit transit, AStarNode endingNode, TimeSpan time)
        {
            ITransit directTransit = null;

            var originalWeight          = endingNode.Weight;
            var originalHeuristicWeight = endingNode.HeuristicWeight;

            // We are not interested in direct paths by feet, as it will most likely won't be the best path.
            // If it is A* will find it in the main part of the algorithm.
            if (transit.Transport.Alias != "Feet" && transit.Transport.IsTransitPossible(transit.StartNode.Location, endingNode.Location))
            {
                directTransit           = new Transit();
                directTransit.Transport = transit.Transport;
                directTransit.StartNode = transit.StartNode;
                directTransit.EndNode   = endingNode;

                var potentialWeight    = _weightCalculator.CalculateWeight(directTransit, time) * 0.75 + ((AStarNode)transit.StartNode).Weight;
                var potentialHeuristic = _heuristicCalculator.CalculateWeight(transit, time);
                endingNode.Weight          = potentialWeight;
                endingNode.HeuristicWeight = potentialHeuristic;

                directTransit.DepartureTime = directTransit.Transport.GetClosestDepartureTime(directTransit.StartNode.Location, time);
                directTransit.ArrivalTime   = directTransit.DepartureTime + directTransit.Transport.TravelTime(directTransit.StartNode.Location, directTransit.EndNode.Location, directTransit.DepartureTime);
            }

            AStarPath path = BacktrackPath(directTransit);

            // Reset ending node weight as to not interfere with the main part of the algorithm
            endingNode.Weight          = originalWeight;
            endingNode.HeuristicWeight = originalHeuristicWeight;

            return(Tuple.Create(path.Value > 0, path));
        }
Пример #4
0
    public void FixedUpdate()
    {
        if (mPath == null)
        {
            //We have no path to move after yet
            return;
        }

        if (mCurrentWaypoint >= mPath.Count())
        {
            Debug.Log("End Of Path Reached");
            mPath = null;

            movingDirection = Vector2.zero;

            return;
        }

        //Direction to the next waypoint
        Vector3 dir = (mPath.GetNode(mCurrentWaypoint).transform.position - transform.position).normalized;

        movingDirection = dir;

        dir *= mSpeed * Time.fixedDeltaTime;
        transform.position += dir;

        //Check if we are close enough to the next waypoint
        //If we are, proceed to follow the next waypoint
        if (Vector3.Distance(transform.position, mPath.GetNode(mCurrentWaypoint).transform.position) < mTargetDistance)
        {
            mCurrentWaypoint++;
            return;
        }
    }
Пример #5
0
 void Start()
 {
     ASPath = new AStarPath(WorldController.Instance.graph);
     path   = new List <Tile> ();
     //just for debugging
     //DrawPathLine = true;
 }
Пример #6
0
    void CalcEnemyPath(GameCube startCube, AStarPath suppliedPath = null)
    {
        RemoveEnemyPathUI(startCube);

        List <GameObject> pathTrails = new List <GameObject> ();
        List <GameCube>   cachedPath = new List <GameCube> ();

        AStarPath path = (suppliedPath != null) ? suppliedPath : new AStarPath(startCube, enemyDestination);

        if (path.IsComplete == false)
        {
            Debug.LogError("Enemy Path Completely Blocked!");
        }

        cachedPath.Add(startCube);
        while (path.IsNext())
        {
            cachedPath.Add(path.GetNext());
        }

        for (float i = 0; i < cachedPath.Count; i++)
        {
            pathTrails.Add(SpawnEnemyPathUI(cachedPath, (int)i, pathTrails));
        }

        currentPaths [startCube]      = cachedPath;
        currentPathTrails [startCube] = pathTrails;
    }
Пример #7
0
    protected void Move(Vector2 position)
    {
        state = EnemyState.MOVE;
        // transform.position = Vector2.MoveTowards(transform.position, position, moveSpeed * Time.deltaTime);

        Vector2 tilePos       = AStarPath.GetTilePosition(transform.position);
        Vector2 playerTilePos = AStarPath.GetTilePosition(player.transform.position);

        path = AStarPath.FindPath(tilePos, playerTilePos);

        if (path != null)
        {
            path.Reverse();

            List <Vector2> pathWorldPosition = new List <Vector2>();
            for (int i = 0; i < path.Count; i++)
            {
                pathWorldPosition.Add(AStarPath.GetTileWorldPosition(path[i].position));
            }

            if (followEnumerator != null)
            {
                StopCoroutine(followEnumerator);
            }

            followEnumerator = FollowPath(pathWorldPosition, player.transform.position);

            StartCoroutine(followEnumerator);
        }
    }
    public Color[] generateRoadMask(int roadCount, int minRoadLength)
    {
        int width = (int)Mathf.Sqrt(fullHeightMap.Length);

        Color[] colors = new Color[fullHeightMap.Length];
        for (int x = 0; x < width * width; x++)
        {
            colors[x] = new Color(255, 255, 255);
        }
        for (int i = 0; i < roadCount; i++)
        {
            Vector2 pointA = new Vector2(Random.Range(0, width), Random.Range(0, width));
            Vector2 pointB;
            do
            {
                pointB = new Vector2(Random.Range(0, width), Random.Range(0, width));
            } while (AStarPath.manhattanDistanceHeuristic(pointA, pointB) < minRoadLength);

            Debug.Log("Start: " + pointA + "   End: " + pointB);

            List <Vector2> path = AStarPath.findPath(pointA, pointB, width, fullHeightMap, heightMultiplier);
            foreach (Vector2 point in path)
            {
                int roadMapIndex = (int)(point.y * width + point.x);
                colors[roadMapIndex] = new Color(0, 0, 0);
                List <int> neighbors = AStarPath.getGridNeighbors(roadMapIndex, width);
                foreach (int index in neighbors)
                {
                    colors[index] = new Color(0, 0, 0);
                }
            }
        }
        return(colors);
    }
Пример #9
0
    void MovementMouseUI(Hex mouseHex)
    {
        //button needs to be disabled if the player is moving or has the ball
        //need to be able to free throw - different UI

        hexOutliner.SetActive(true);
        hexOutliner.transform.position = mouseHex.Position + outlinerOffset;

        if (selected != null)
        {
            if (selected.Moving == false && selected.MoveHexesInRange.Contains(mouseHex))
            {
                AStarPath p = new AStarPath(GridManager.Instance.Grid, selected.CurrentHex, mouseHex, true);

                List <Vector3> hexPositions = new List <Vector3> ();

                LineRenderer lr = selected.GetComponent <LineRenderer> ();
                lr.enabled = true;

                hexPositions.Add(selected.transform.position + outlinerOffset - selected.HexOffset);
                while (p.IsNextHex())
                {
                    hexPositions.Add(p.GetNextHex().Position + outlinerOffset);
                }

                lr.positionCount = hexPositions.Count;

                lr.SetPositions(hexPositions.ToArray());
            }
            else
            {
                selected.GetComponent <LineRenderer> ().enabled = false;
            }
        }
    }
Пример #10
0
    public void GenerateGrid()
    {
        map = CreateNodesFromTilemaps.CreateNodes(grid, floor, obstacleLayers, transform);

        SpawnNodes(map, false);
        AStarPath.SaveMap(map);

        path = AStarPath.FindPath(new Vector2(-7.9f, -.2f), new Vector2(-.1f, -.1f));
        StartCoroutine(DelayedPath());
    }
Пример #11
0
        private AStarPath BacktrackPath(ITransit transit)
        {
            var path = new AStarPath();

            if (transit == null)
            {
                return(path);
            }

            path.Add(transit);
            return(BacktrackPath(transit.StartNode, path));
        }
Пример #12
0
        public twin StepTowardsTarget(twin mover, twin target)
        {
            var path = new AStarPath(this.robotPather, mover, target);

            if (path.cost > 0 && path.cells.Count > 1)
            {
                return(path.cells[1] - mover);
            }

            // else: there is no path
            return(twin.zero);
        }
Пример #13
0
    IEnumerator GetPath(Point destination)
    {
        AStarPath aPath = new AStarPath(map.Maps);
        Point startPoint = new Point(row, column);
        IList<Point> list = aPath.GetPath(startPoint, destination);

        if (null == list || list.Count == 0) yield break;

        list.RemoveAt(0);//第一个为自身位置

        targetPosEffect.SetActive(true);
        Vector3 effectPos = Map.Instance.GetGridPos(list[list.Count - 1].R, list[list.Count - 1].C);
        effectPos.z = targetPosEffect.transform.position.z;

        targetPosEffect.transform.position = effectPos;
        if (null != hideEffectCoroutine) StopCoroutine(hideEffectCoroutine);
        hideEffectCoroutine =StartCoroutine(HideEffectObj());

        Animation animation = player.GetComponent<Animation>();

        for (int i = 0; i < list.Count; i++)
        {
            Point p = list[i];
            Vector3 _pos = GetWorldPos(list[i].R, list[i].C);

             Vector3 targetPos = new Vector3(_pos.x, _pos.y, transform.position.z);
            //设置层级
            rendqueue = map.Maps[list[i].R, list[i].C].SortOrder + 1;
            playerRender.material.renderQueue = rendqueue;
            targetPos = GetChangePos(targetPos);

            //获取转向
            eDirectionType direction = MapHelper.GetNextDirection(row, column, list[i].R, list[i].C);
            RotatePlayer(direction, player);
            animation.Play("run");
            while (Vector3.Distance(transform.position, targetPos) > 0.01f)
            {
                yield return new WaitForSeconds(Time.deltaTime);
                transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);

            }

            row = list[i].R;
            column = list[i].C;
            targetPosEffect.SetActive(false);
        }
        animation.Play("idle");
        Debug.Log(string.Format("寻路完成:{0}_{1}",row,column));
        playerRender.material.renderQueue = rendqueue;
    }
Пример #14
0
    public static AStarPath GetPath(Vector3 vStartPosition, Vector3 vEndPosition)
    {
        AStarPath path             = new AStarPath();
        AStarNode pStartNode       = GetClosestNode(vStartPosition);
        AStarNode pEndNode         = GetClosestNode(vEndPosition);
        Vector3   vEndNodePosition = pEndNode.transform.position;
        Dictionary <AStarNode, AStarNodeInfo> nodeInfos = new Dictionary <AStarNode, AStarNodeInfo>();
        List <AStarNodeInfo> openList   = new List <AStarNodeInfo>();
        List <AStarNode>     closedList = new List <AStarNode>();

        // Add start node to open list
        AddNodeToOpenList(pStartNode, null, nodeInfos, openList, closedList, vEndNodePosition);

        AStarNodeInfo pFinalNode = null;

        while (openList.Count > 0)
        {
            // Examine node
            AStarNodeInfo pCurrentNode = openList[0];
            openList.RemoveAt(0);

            if (pCurrentNode.mNode == pEndNode)
            {
                pFinalNode = pCurrentNode;

                break;
            }

            else
            {
                foreach (AStarNode pNode in pCurrentNode.mNode.Links)
                {
                    AddNodeToOpenList(pNode, pCurrentNode, nodeInfos, openList, closedList, vEndNodePosition);
                }
            }
        }

        // Retrace path
        if (pFinalNode != null)
        {
            AStarNodeInfo pNode = pFinalNode;
            while (pNode != null)
            {
                path.InsertNode(pNode.mNode);
                pNode = pNode.mPreviousNode;
            }
        }

        return(path);
    }
    public Stack <Coordinate> FindRandomPath(Vector3 objectPosition)
    {
        var start = Maze[(int)Math.Round(objectPosition.x) / mazeScale, (int)Math.Round(objectPosition.z) / mazeScale];

        var end = Maze[UnityEngine.Random.Range(1, MazeWidth - 2), UnityEngine.Random.Range(1, MazeWidth - 2)];

        while (end.type != MazeID.SPACE)
        {
            end = Maze[UnityEngine.Random.Range(1, MazeWidth - 2), UnityEngine.Random.Range(1, MazeWidth - 2)];
        }

        AStarPath pathfinder = new AStarPath(Maze, start, end, MazeWidth, MazeHeight);

        return(pathfinder.FindPath());
    }
Пример #16
0
    /// <summary>
    /// Begins A* pathfinding using the A* algorithm
    /// Copies the grid to an object and begins to traverse this 
    /// new grid finding a path to target node
    /// </summary>
    /// <param name="startPos">Start position.</param>
    /// <param name="targetPos">Target position.</param>
    /// <param name="lineOfSight">If set to <c>true</c> line of sight.</param>
    /// <param name="callback">Callback.</param>
    /// <param name="pathId">Path identifier.</param>
    public IEnumerator AStarPathfinding(Vector3 startPos, Vector3 targetPos, bool lineOfSight, Action<Vector3[], bool> callback, int pathId, float totalMs)
    {
        //Added for mesh copy O(n2) heavy
        Node[,] meshCopy = grid.GetGridCopy();

        //Done for frame processing take over
        yield return null;

        UnityEngine.Debug.Log("Going into A* Thread");
        AStarPath aStar = new AStarPath(grid, meshCopy, startPos, targetPos, lineOfSight, callback, pathId, totalMs);
        paths.Add(aStar);

        //Starts a new thread using threadpool management
        ThreadPool.QueueUserWorkItem(aStar.ThreadPoolCallback, paths.Count);
    }
Пример #17
0
    // Use this for initialization
    void Start()
    {
        this.spawned = 0;

        //The only way to create a new object from scratch is to attach it to a new object:
        pathObj = new GameObject("PathSystem");
        pathObj.transform.parent = this.transform;
        pathObj.transform.localPosition = Vector3.zero;

        //This is the only way to create a component properly:
        path = pathObj.AddComponent<AStarPath>();

        //If the world changes we need to recompute:
        GenerateWorld.WorldCubeData.CellAdded += (obj) => { this.validPath = false; };
        GenerateWorld.WorldCubeData.CellRemoved += (obj) => { this.validPath = false; };
    }
Пример #18
0
 public void GetPathTo(twin target, out twin move, out AStarPath path)
 {
     move = twin.zero;
     path = new AStarPath(pather, my_cell_pos, target);
     if (path.cells == null)
     {
         return;
     }
     foreach (var cell in path.cells)
     {
         if (cell != my_cell_pos)
         {
             move = cell - my_cell_pos;
             return;
         }
     }
 }
Пример #19
0
        private AStarPath BacktrackPath(INode endNode, AStarPath existingPath = null)
        {
            var path = existingPath ?? new AStarPath();

            var currentNode = endNode;

            while (true)
            {
                if (currentNode.FastestTransit == null)
                {
                    break;
                }

                path.Add(currentNode.FastestTransit);
                currentNode = (AStarNode)currentNode.FastestTransit.StartNode;
            }

            return(path);
        }
Пример #20
0
    IEnumerator MoveCoroutine(Hex destHex)
    {
        moving = true;

        if (onMoveBegan != null)
        {
            onMoveBegan(this);
        }

        HideMovementHexes();

        AStarPath p = new AStarPath(GridManager.Instance.Grid, currentHex, destHex, true);

        Hex next;

        Hex current = CurrentHex;

        destOccupant = destHex.Occupant;
        CurrentHex   = destHex;

        while (p.IsNextHex())
        {
            next = p.GetNextHex();

            CheckHex(next.Occupant);

            if (movesInActionRemaining >= next.MoveCost)
            {
                yield return(StartCoroutine(MoveToHex(current, next)));
            }

            current = next;
        }

        onMoveComplete(this);

        if (UserControlManager.Instance.Selected == this)
        {
            ShowMovementHexes();
        }

        moving = false;
    }
        private static Point GetTileNextToBuilding(int tileX, int tileY, AStarGraph graph)
        {
            AStarNode tileNode = graph.GetNode(tileX, tileY);

            if (tileNode is not null)
            {
                tileNode.FakeTileClear = true;

                AStarPath path = graph.FindPathWithBubbleCheck(graph.FarmerNodeOffset, tileNode);

                if (path is not null && path.Count > 0)
                {
                    return(new Point(tileX, tileY));
                }

                tileNode.FakeTileClear = false;
            }

            return(Point.Zero);
        }
Пример #22
0
    public bool SetDestination(BasePath path, BasePathNode newTargetNode, float speedFraction)
    {
        if (!AI.move)
        {
            return(false);
        }
        if (!AI.navthink)
        {
            return(false);
        }
        paused = false;
        if (!CanUseAStar)
        {
            return(false);
        }
        if (newTargetNode == targetNode && HasPath)
        {
            return(true);
        }
        if (ReachedPosition(newTargetNode.transform.position))
        {
            return(true);
        }
        BasePathNode closestToPoint = path.GetClosestToPoint(base.transform.position);

        if (closestToPoint == null || closestToPoint.transform == null)
        {
            return(false);
        }
        float pathCost;

        if (AStarPath.FindPath(closestToPoint, newTargetNode, out currentAStarPath, out pathCost))
        {
            currentSpeedFraction = speedFraction;
            targetNode           = newTargetNode;
            SetCurrentNavigationType(NavigationType.AStar);
            Destination = newTargetNode.transform.position;
            return(true);
        }
        return(false);
    }
Пример #23
0
    //When we delete something, does it open a shorter path?
    public void ShouldRecalcPathRemoved()
    {
        Debug.Log("Called");

        Dictionary <GameCube, List <GameCube> > paths = new Dictionary <GameCube, List <GameCube> > ();

        foreach (KeyValuePair <GameCube, List <GameCube> > kvp in currentPaths)
        {
            paths [kvp.Key] = currentPaths [kvp.Key];
        }

        foreach (KeyValuePair <GameCube, List <GameCube> > path in paths)
        {
            AStarPath newPath = new AStarPath(path.Key, enemyDestination);

            if (newPath.Length() < path.Value.Count)
            {
                CalcEnemyPath(path.Key, newPath);
            }
        }
    }
Пример #24
0
    /*
     * THere should always be a path the enemies can take from (each) start cube to
     * the enemy destination
     */
    public bool WouldYieldNoPaths(GameCube test, float newMoveCost)
    {
        // set test cube to Mathf.Infinity
        float testMoveCost = test.MoveCost;

        test.MoveCost = newMoveCost;

        foreach (GameCube start in startCubes)
        {
            AStarPath path = new AStarPath(start, enemyDestination);

            if (path.IsComplete == false)
            {
                test.MoveCost = testMoveCost;

                return(false);
            }
        }

        test.MoveCost = testMoveCost;

        //there is at least one path for each start cube
        return(true);
    }
Пример #25
0
 // Use this for initialization
 void Start()
 {
     pathGenerator = new AStarPath();
 }
Пример #26
0
    public void UpdateMovement_Hunt()
    {
        if (Interface.CallHook("OnBradleyApcHunt", this) != null || patrolPath == null)
        {
            return;
        }
        TargetInfo targetInfo = targetList[0];

        if (!targetInfo.IsValid())
        {
            return;
        }
        if (HasPath() && targetInfo.IsVisible())
        {
            if (currentPath.Count > 1)
            {
                Vector3 item = currentPath[currentPathIndex];
                ClearPath();
                currentPath.Add(item);
                finalDestination = item;
                currentPathIndex = 0;
            }
        }
        else
        {
            if (!(UnityEngine.Time.time > nextEngagementPathTime) || HasPath() || targetInfo.IsVisible())
            {
                return;
            }
            bool                flag  = false;
            BasePathNode        start = patrolPath.GetClosestToPoint(base.transform.position);
            List <BasePathNode> nodes = Facepunch.Pool.GetList <BasePathNode>();
            if (GetEngagementPath(ref nodes))
            {
                flag  = true;
                start = nodes[nodes.Count - 1];
            }
            BasePathNode        basePathNode = null;
            List <BasePathNode> nearNodes    = Facepunch.Pool.GetList <BasePathNode>();
            patrolPath.GetNodesNear(targetInfo.lastSeenPosition, ref nearNodes, 30f);
            Stack <BasePathNode> stack = null;
            float num = float.PositiveInfinity;
            float y   = mainTurretEyePos.localPosition.y;
            foreach (BasePathNode item2 in nearNodes)
            {
                Stack <BasePathNode> path = new Stack <BasePathNode>();
                float pathCost;
                if (targetInfo.entity.IsVisible(item2.transform.position + new Vector3(0f, y, 0f)) && AStarPath.FindPath(start, item2, out path, out pathCost) && pathCost < num)
                {
                    stack        = path;
                    num          = pathCost;
                    basePathNode = item2;
                }
            }
            if (stack == null && nearNodes.Count > 0)
            {
                Stack <BasePathNode> path2         = new Stack <BasePathNode>();
                BasePathNode         basePathNode2 = nearNodes[UnityEngine.Random.Range(0, nearNodes.Count)];
                float pathCost2;
                if (AStarPath.FindPath(start, basePathNode2, out path2, out pathCost2) && pathCost2 < num)
                {
                    stack        = path2;
                    basePathNode = basePathNode2;
                }
            }
            if (stack != null)
            {
                currentPath.Clear();
                if (flag)
                {
                    for (int i = 0; i < nodes.Count - 1; i++)
                    {
                        currentPath.Add(nodes[i].transform.position);
                    }
                }
                foreach (BasePathNode item3 in stack)
                {
                    currentPath.Add(item3.transform.position);
                }
                currentPathIndex = -1;
                pathLooping      = false;
                finalDestination = basePathNode.transform.position;
            }
            Facepunch.Pool.FreeList(ref nearNodes);
            Facepunch.Pool.FreeList(ref nodes);
            nextEngagementPathTime = UnityEngine.Time.time + 5f;
        }
    }
Пример #27
0
 public void SetManualDest(int x, int y)
 {
     ASPath = new AStarPath(WorldController.Instance.graph);
     AStarFindPathTo(WorldController.Instance.GetTileAt(x, y));
 }
Пример #28
0
    public void UpdateMovement_Patrol()
    {
        if (patrolPath == null || UnityEngine.Time.time < nextPatrolTime)
        {
            return;
        }
        nextPatrolTime = UnityEngine.Time.time + 20f;
        if ((HasPath() && !IsAtFinalDestination()) || Interface.CallHook("OnBradleyApcPatrol", this) != null)
        {
            return;
        }
        PathInterestNode    randomInterestNodeAwayFrom = patrolPath.GetRandomInterestNodeAwayFrom(base.transform.position);
        BasePathNode        closestToPoint             = patrolPath.GetClosestToPoint(randomInterestNodeAwayFrom.transform.position);
        BasePathNode        basePathNode = null;
        bool                flag         = false;
        List <BasePathNode> nodes        = Facepunch.Pool.GetList <BasePathNode>();

        if (GetEngagementPath(ref nodes))
        {
            flag         = true;
            basePathNode = nodes[nodes.Count - 1];
        }
        else
        {
            basePathNode = patrolPath.GetClosestToPoint(base.transform.position);
        }
        if (!(Vector3.Distance(finalDestination, closestToPoint.transform.position) > 2f))
        {
            return;
        }
        if (closestToPoint == basePathNode)
        {
            currentPath.Clear();
            currentPath.Add(closestToPoint.transform.position);
            currentPathIndex = -1;
            pathLooping      = false;
            finalDestination = closestToPoint.transform.position;
        }
        else
        {
            Stack <BasePathNode> path;
            float pathCost;
            if (!AStarPath.FindPath(basePathNode, closestToPoint, out path, out pathCost))
            {
                return;
            }
            currentPath.Clear();
            if (flag)
            {
                for (int i = 0; i < nodes.Count - 1; i++)
                {
                    currentPath.Add(nodes[i].transform.position);
                }
            }
            foreach (BasePathNode item in path)
            {
                currentPath.Add(item.transform.position);
            }
            currentPathIndex = -1;
            pathLooping      = false;
            finalDestination = closestToPoint.transform.position;
        }
    }
Пример #29
0
        void GenerateRandomGrid()
        {
            var gridArea   = TestGrid.GetGridArea();
            var width      = gridArea.Width;
            var height     = gridArea.Height;
            var grid       = new List <GridTile> ();
            var gridModels = new List <GridModel> ();


            ClearGridParent();


            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x)
                {
                    var gt = Instantiate(gridPrefab, GridParent);
                    gt.name = (x + "," + y);
                    gt.transform.localPosition = new Vector3(x, y, GridParent.transform.position.z);
                    grid.Add(gt);
                    gridModels.Add(new GridModel(gt));
                }
            }
            gridArea.SetGrids(gridModels);

            var cpu         = TestGrid.GetCpu();
            var cpuModel    = GridUtility.GetEmptyGrid(gridArea);
            var cpuLocation = gridArea.GetCellLocation(cpuModel.Cells.First()); //need PORTS and ENTRANCE

            cpuModel.GridComponents.Add(cpu);
            var componentScript = cpuModel.GridTile.gameObject.GetComponent <ComponentScript>();

            componentScript.CreateComponent(cpu);

            //empty.GridTile.SetState(empty);

            var boostChip         = TestGrid.GetBoostChip();
            var boostModel        = GridUtility.GetEmptyGrid(gridArea);
            var boostChipLocation = gridArea.GetCellLocation(boostModel.Cells.First());//need PORTS and ENTRANCE

            boostModel.AddComponent(boostChip);
            componentScript = boostModel.GridTile.gameObject.GetComponent <ComponentScript>();
            componentScript.CreateComponent(boostChip);
            boostModel.GridTile.SetState(boostModel);

            var componentCount = 4;
            var usedTiles      = new List <GridTile> ();
            var max            = grid.Count;
            int i = 0;

            List <GridAreaLocation> recvrLocations = new List <GridAreaLocation>();

            while (i < componentCount)
            {
                var receiverModel = GridUtility.GetEmptyGrid(gridArea);


                var gridComponent = new GridComponent();
                gridComponent.Color = GameUtility.GetRandomColor();
                var c     = new CellLocation(Random.Range(0, 3), Random.Range(0, 3));
                var rCell = receiverModel.GetCell(c);// testing, picking first cell of the grid
                recvrLocations.Add(gridArea.GetCellLocation(rCell));

                gridComponent.CellLocations.Add(c);
                receiverModel.AddComponent(gridComponent);

                componentScript = receiverModel.GridTile.gameObject.GetComponent <ComponentScript>();
                componentScript.CreateComponent(gridComponent);
                ++i;
                receiverModel.GridTile.SetState(receiverModel);
            }

            List <GridPath> paths = new List <GridPath>();

            foreach (var r in recvrLocations)
            {
                var gp = new GridPath();
                gp.StartEntrance  = r;
                gp.FinishEntrance = cpuLocation;

                AStarPath aStar = new AStarPath();
                var       path  = aStar.FindPath(r, cpuLocation, gridArea);
                gp.Path = path;
                //GridUtility.GeneratePath(gp, gridArea);

                paths.Add(gp);
            }


            GridUtility.SetCellStates(paths, gridArea);
            gridModels.ForEach(x => x.GridTile.SetState(x));
            //gridComponent.Cell.Location = new CellLocation { X = 0, Y = 1 };
            //componentScript.CreateComponent (gridComponent);


            //g.gameObject.AddComponent<ComponentScript> ();
        }
Пример #30
0
    public void UpdateMovement_Hunt()
    {
        float single;

        if (Interface.CallHook("OnBradleyApcHunt", this) != null)
        {
            return;
        }
        if (this.patrolPath == null)
        {
            return;
        }
        BradleyAPC.TargetInfo item = this.targetList[0];
        if (item.IsValid())
        {
            if (this.HasPath() && item.IsVisible())
            {
                if (this.currentPath.Count > 1)
                {
                    Vector3 vector3 = this.currentPath[this.currentPathIndex];
                    this.ClearPath();
                    this.currentPath.Add(vector3);
                    this.finalDestination = vector3;
                    this.currentPathIndex = 0;
                    return;
                }
            }
            else if (UnityEngine.Time.time > this.nextEngagementPathTime && !this.HasPath() && !item.IsVisible())
            {
                bool                flag           = false;
                BasePathNode        closestToPoint = this.patrolPath.GetClosestToPoint(base.transform.position);
                List <BasePathNode> list           = Facepunch.Pool.GetList <BasePathNode>();
                if (this.GetEngagementPath(ref list))
                {
                    flag           = true;
                    closestToPoint = list[list.Count - 1];
                }
                BasePathNode        basePathNode  = null;
                List <BasePathNode> basePathNodes = Facepunch.Pool.GetList <BasePathNode>();
                this.patrolPath.GetNodesNear(item.lastSeenPosition, ref basePathNodes, 30f);
                Stack <BasePathNode> basePathNodes1 = null;
                float single1 = Single.PositiveInfinity;
                float single2 = this.mainTurretEyePos.localPosition.y;
                foreach (BasePathNode basePathNode1 in basePathNodes)
                {
                    Stack <BasePathNode> basePathNodes2 = new Stack <BasePathNode>();
                    if (!item.entity.IsVisible(basePathNode1.transform.position + new Vector3(0f, single2, 0f), Single.PositiveInfinity) || !AStarPath.FindPath(closestToPoint, basePathNode1, out basePathNodes2, out single) || single >= single1)
                    {
                        continue;
                    }
                    basePathNodes1 = basePathNodes2;
                    single1        = single;
                    basePathNode   = basePathNode1;
                }
                if (basePathNodes1 != null)
                {
                    this.currentPath.Clear();
                    if (flag)
                    {
                        for (int i = 0; i < list.Count - 1; i++)
                        {
                            this.currentPath.Add(list[i].transform.position);
                        }
                    }
                    foreach (BasePathNode basePathNode2 in basePathNodes1)
                    {
                        this.currentPath.Add(basePathNode2.transform.position);
                    }
                    this.currentPathIndex = -1;
                    this.pathLooping      = false;
                    this.finalDestination = basePathNode.transform.position;
                }
                Facepunch.Pool.FreeList <BasePathNode>(ref basePathNodes);
                Facepunch.Pool.FreeList <BasePathNode>(ref list);
                this.nextEngagementPathTime = UnityEngine.Time.time + 5f;
            }
        }
    }
Пример #31
0
 public void OnEnable()
 {
     aStarPathScript = target as AStarPath;
     aStarPathScript.OnDrawGizmosCallback = OnDrawGizmos;
 }
Пример #32
0
    public void UpdateMovement_Patrol()
    {
        float single;
        Stack <BasePathNode> basePathNodes;

        if (this.patrolPath == null)
        {
            return;
        }
        if (UnityEngine.Time.time < this.nextPatrolTime)
        {
            return;
        }
        this.nextPatrolTime = UnityEngine.Time.time + 20f;
        if (this.HasPath() && !this.IsAtFinalDestination())
        {
            return;
        }
        if (Interface.CallHook("OnBradleyApcPatrol", this) != null)
        {
            return;
        }
        PathInterestNode    randomInterestNodeAwayFrom = this.patrolPath.GetRandomInterestNodeAwayFrom(base.transform.position, 10f);
        BasePathNode        closestToPoint             = this.patrolPath.GetClosestToPoint(randomInterestNodeAwayFrom.transform.position);
        BasePathNode        item = null;
        bool                flag = false;
        List <BasePathNode> list = Facepunch.Pool.GetList <BasePathNode>();

        if (!this.GetEngagementPath(ref list))
        {
            item = this.patrolPath.GetClosestToPoint(base.transform.position);
        }
        else
        {
            flag = true;
            item = list[list.Count - 1];
        }
        if (Vector3.Distance(this.finalDestination, closestToPoint.transform.position) > 2f)
        {
            if (closestToPoint == item)
            {
                this.currentPath.Clear();
                this.currentPath.Add(closestToPoint.transform.position);
                this.currentPathIndex = -1;
                this.pathLooping      = false;
                this.finalDestination = closestToPoint.transform.position;
                return;
            }
            if (AStarPath.FindPath(item, closestToPoint, out basePathNodes, out single))
            {
                this.currentPath.Clear();
                if (flag)
                {
                    for (int i = 0; i < list.Count - 1; i++)
                    {
                        this.currentPath.Add(list[i].transform.position);
                    }
                }
                foreach (BasePathNode basePathNode in basePathNodes)
                {
                    this.currentPath.Add(basePathNode.transform.position);
                }
                this.currentPathIndex = -1;
                this.pathLooping      = false;
                this.finalDestination = closestToPoint.transform.position;
            }
        }
    }
Пример #33
0
 public void WalkTo(Vector3 vPosition)
 {
     mPath            = AStarGraph.GetPath(transform.position, vPosition);
     mCurrentWaypoint = 0;
 }
Пример #34
0
        private void _handleMovement()
        {
            // Do not move if we do not have a path to move to!
            if (PathName == null)
            {
                return;
            }

            // Do not move the mob if its dead. corpses dont move!
            if (_mobAttributesMono.Dead)
            {
                return;
            }

            // Do not move if not tracked.
            if (MobNumber == 0)
            {
                return;
            }

            if (NetworkingManager.Instance.IsServer)
            {
                #region Server-sided movement handler

                #region Continuously find the platform and path objects.

                if (_mapPlatform == null)
                {
                    _mapPlatform = MapPlatform.Instance;
                    return;
                }

                if (_pathObject == null)
                {
                    AStarPath.AStarPathDictionary.TryGetValue(PathName, out _pathObject);
                    if (!_pathObject)
                    {
                        return;
                    }
                    _path          = _pathObject.GetComponent <AStarPath>();
                    _currPathIndex = _path.CompactPath.Count - 1;
                    _currPathList  = new List <Vector3>(_path.CompactPath);
                    Destination    = _currPathList[_currPathIndex];
                    return;
                }

                #endregion

                #region Check for path object and a checkpoint list.

                if (_path == null)
                {
                    return;
                }

                if (_currPathList.Count == 0)
                {
                    _currPathList  = new List <Vector3>(_path.CompactPath);
                    _currPathIndex = _currPathList.Count - 1;
                    Destination    = _currPathList[_currPathIndex];
                    _mobModifierRpc.UpdateMoveStateSendRpc(MobNumber, transform.position, Destination);
                    return;
                }

                #endregion

                var currPos = transform.position;
                var endPos  = _mobAttributesMono.Flying ? _currPathList[0] : Destination;
                endPos.y = currPos.y;
                var dir = Vector3.Normalize(endPos - currPos);
                var remainingDistance = Vector3.Distance(currPos, endPos);
                var travelDistance    = _mobAttributesMono.MoveSpeed * Time.fixedDeltaTime;
                var nextPosition      = currPos + (dir * travelDistance);

                var distanceAvaliable = remainingDistance > travelDistance;
                var nextPosIsBlocked  = _mapPlatform.LocationIsBlocked(nextPosition);

                #region Blocked path handler.

                if (nextPosIsBlocked && !_mobAttributesMono.Flying)
                {
                    List <Vector3> placeHolder;
                    _mapPlatform.FindAStarPath(currPos, _path.EndPoint.transform.position, out _currPathList, out placeHolder);
                    _currPathIndex = _currPathList.Count - 1;
                    Destination    = _currPathList[_currPathIndex];
                    _mobModifierRpc.UpdateMoveStateSendRpc(MobNumber, transform.position, Destination);
                    return;
                }

                #endregion

                #region Movement and path change handler.

                if (distanceAvaliable)
                {
                    transform.position = nextPosition;
                }
                else
                {
                    transform.position = endPos;

                    if (--_currPathIndex >= 0)
                    {
                        Destination = _currPathList[_currPathIndex];
                        _mobModifierRpc.UpdateMoveStateSendRpc(MobNumber, transform.position, Destination);
                    }
                    else
                    {
                        var nextPath = _path.NextPath.GetComponent <AStarPath>();
                        _path = (nextPath == null || nextPath == _path) ? null : nextPath;
                        if (_path != null)
                        {
                            _currPathIndex = _path.CompactPath.Count - 1;
                            _currPathList  = new List <Vector3>(_path.CompactPath);
                            Destination    = _currPathList[_currPathIndex];
                            _mobModifierRpc.UpdateMoveStateSendRpc(MobNumber, transform.position, Destination);
                        }
                    }
                }

                if (_prevLocation != transform.position)
                {
                    transform.LookAt(2 * transform.position - _prevLocation);
                }
                _prevLocation = transform.position;

                #endregion

                #endregion
            }
            else
            {
                #region Client-sided movement handler

                if (transform.position != Destination)
                {
                    transform.LookAt(Destination);
                }

                var currPos = transform.position;
                var endPos  = Destination;
                endPos.y = currPos.y;
                var dir = Vector3.Normalize(endPos - currPos);
                var remainingDistance = Vector3.Distance(currPos, endPos);
                var travelDistance    = _mobAttributesMono.MoveSpeed * Time.fixedDeltaTime;
                var nextPosition      = currPos + (dir * travelDistance);

                var distanceAvaliable = remainingDistance > travelDistance;

                if (distanceAvaliable)
                {
                    transform.position = nextPosition;
                }

                #endregion
            }
        }