GetNearest() public method

public GetNearest ( Vector3 position ) : NNInfo
position Vector3
return Pathfinding.NNInfo
Example #1
0
        private bool BlupeesAreReachable()
        {
            var doorNode = Graph.GetNearest(Doors[0].transform.position);

            var loots = Chests.Select(c => c.transform.position)
                        .Concat(Pots.Select(p => p.transform.position))
                        .ToArray();

            for (var i = 0; i < loots.Length; ++i)
            {
                var loot = loots[i];

                var left  = Graph.GetNearest(loot + Vector3.left * GridHelper.Instance.TileSize.x);
                var right = Graph.GetNearest(loot + Vector3.right * GridHelper.Instance.TileSize.x);
                var up    = Graph.GetNearest(loot + Vector3.up * GridHelper.Instance.TileSize.y);
                var down  = Graph.GetNearest(loot + Vector3.down * GridHelper.Instance.TileSize.y);

                var possible =
                    PathUtilities.IsPathPossible(doorNode.node, left.node) ||
                    PathUtilities.IsPathPossible(doorNode.node, right.node) ||
                    PathUtilities.IsPathPossible(doorNode.node, up.node) ||
                    PathUtilities.IsPathPossible(doorNode.node, down.node);

                if (!possible)
                {
                    return(false);
                }
            }

            return(true);
        }
Example #2
0
 public void CalcNodes()
 {
     Nodes.Clear();
     NodeObjs = GetComponentsInChildren <Transform>();
     if (NodeObjs != null)
     {
         foreach (var item in NodeObjs)
         {
             if (item == transform)
             {
                 transform.localPosition = Vector3.zero;
                 continue;
             }
             GraphNode node = null;
             if (Application.isPlaying)
             {
                 node = AStarMgr.GetSafeNode(item.position);
             }
             else
             {
                 node = AstarPath.GetNearest(item.position).node;
             }
             if (node == null)
             {
                 CLog.Error("错误! 没有Node");
                 continue;
             }
             Nodes.Add(node);
             item.position = (Vector3)node.position;
             item.name     = "Item";
         }
     }
 }
Example #3
0
    // Start is called before the first frame update
    void Start()
    {
        if (Application.isEditor)
        {
            AstarPath path = GetComponent <AstarPath>();
            if (path != null)
            {
                var node = path.GetNearest(StartPoint.transform.position).node;
                List <Pathfinding.GraphNode> reachableNodes = Pathfinding.PathUtilities.GetReachableNodes(node);

                using (BinaryWriter writer = new BinaryWriter(File.Open(@".\Maps\" + gameObject.name + ".map", FileMode.Create)))
                {
                    writer.Write(path.data.gridGraph.width);
                    writer.Write(path.data.gridGraph.depth);
                    for (int y = path.data.gridGraph.depth - 1; y >= 0; y--)
                    {
                        for (int x = 0; x < path.data.gridGraph.width; x++)
                        {
                            bool walkable = path.data.gridGraph.nodes[path.data.gridGraph.width * y + x].Walkable && reachableNodes.Contains(path.data.gridGraph.nodes[path.data.gridGraph.width * y + x]);

                            writer.Write(walkable);
                            if (walkable)
                            {
                                writer.Write(path.data.gridGraph.nodes[path.data.gridGraph.width * y + x].position.x / 1000f);
                                writer.Write(path.data.gridGraph.nodes[path.data.gridGraph.width * y + x].position.y / 1000f);
                                writer.Write(path.data.gridGraph.nodes[path.data.gridGraph.width * y + x].position.z / 1000f);
                                //Debug.Log("saving x: " + path.data.gridGraph.nodes[path.data.gridGraph.width * y + x].position.x / 1000f + ", y: " + path.data.gridGraph.nodes[path.data.gridGraph.width * y + x].position.y / 1000f + ", z: " + path.data.gridGraph.nodes[path.data.gridGraph.width * y + x].position.z / 1000f);
                            }
                        }
                    }
                }
            }
        }
    }
Example #4
0
        /// <summary>
        /// Constructor, initialize variables, register resource
        /// </summary>
        /// <param name="position">Position of the Resource</param>
        /// <param name="resourceType">Type of the Resource</param>
        /// <param name="amount">Amount of the Resource</param>
        /// <param name="isInfinite">Is the resource infinite?</param>
        public ResourceSource(Vector3 position, ResourceType resourceType = ResourceType.Water, int amount = 10, bool isInfinite = false)
        {
            m_Position = position;
            AstarPath p = AstarPath.active;

            m_NearestNode        = p.GetNearest(position).node;
            m_ResourceSourceData = new ResourceSourceData(resourceType, amount, isInfinite);
            PlanetDatalayer.Instance.GetManager <ResourceManager>().RegisterResourceSource(this);
        }
Example #5
0
    private bool CheckSquad()
    {
        // Check if it must move to squad

        if (((new Vector2(transform.position.x, transform.position.y) - squad.GetPosition()).magnitude > squad.movementRadius + 0.5) && mode < 3)
        // It won't try to move to the squad, when it's already moving to the squad, or attacking opponents
        {         // move to squad
                  // Is too far away from squad

            bool searching = true;
            int  x         = 25;

            do
            {
                // Create random positions around the squad, until one fits

                Vector2 dir = Random.insideUnitCircle * squad.movementRadius * 0.7f;

                Vector2 newPos = squad.GetPosition() + dir;

                // Find new target position

                float probability = Mathf.Clamp((GetClosestObjectDistance(newPos, GameMaster.entities.ToArray(), true) - 2) * 0.05f, 0.005f, 0.4f);           // Places not near at other entities are more probable

                probability *= Mathf.Clamp(1 - ((new Vector2(transform.position.x, transform.position.y) - newPos).magnitude / 12), 0.2f, 1);                 // Nearer places are more probable

                if (aStarPath.GetNearest(newPos).node.Walkable&& (probability > (float)Random.Range(0f, 1f)))
                {
                    // Found position

                    SetMode(3);
                    searching = false;

                    targetPlace = newPos;
                }

                x--;
            } while (searching && x > 0);

            return(true);
        }

        // Check if it has moved to squad

        else if (mode == 3 && (new Vector2(transform.position.x, transform.position.y) - squad.GetPosition()).magnitude < (squad.movementRadius - 1))
        {
            // It returned to squad

            SetMode(0);
        }

        if (mode == 3)
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Example #6
0
        public void SetWalkable(Vector3 pos, bool b)
        {
            var node = Ins.GetNearest(pos).node;

            node.Walkable = b;
        }
Example #7
0
    private void SpawnSquad(int team, int size)
    {
        if (size == 0)
        {
            return;
        }

        // Find squad location - 100 tries

        Vector2 squadLocation = new Vector2(0, 0);
        float   maxX          = map.mapWidth * map.tileSize * 0.5f - 15;
        float   maxY          = map.mapHeight * map.tileSize * 0.5f - 15;

        bool viable = true;

        for (int i = 0; i < 100; i++)
        {
            // Create random position inside map

            float x = Random.Range(-maxX, maxX);
            float y = Random.Range(-maxY, maxY);
            squadLocation = new Vector2(x, y);

            // Check if viable

            viable = true;
            if (!aStar.GetNearest(squadLocation).node.Walkable)
            {
                viable = false;
                continue;
            }

            // Check if not too near of opponent squad

            GameObject opponentContainer = team == 0 ? gm.enemyContainer : gm.friendContainer;

            for (int g = 0; g < opponentContainer.transform.childCount; g++)
            {
                GameObject squadObject = opponentContainer.transform.GetChild(g).gameObject;

                Squad squad = squadObject.GetComponent <Squad>();

                float distance = (squad.GetPosition() - squadLocation).magnitude - squad.movementRadius;

                if (distance < 15)
                {
                    viable = false;
                }
            }

            if (!viable)
            {
                continue;
            }

            // Check if not too near of friendly squad

            GameObject friendContainer = team == 1 ? gm.enemyContainer : gm.friendContainer;

            for (int g = 0; g < friendContainer.transform.childCount; g++)
            {
                GameObject squadObject = friendContainer.transform.GetChild(g).gameObject;

                Squad squad = squadObject.GetComponent <Squad>();

                float distance = (squad.GetPosition() - squadLocation).magnitude - squad.movementRadius;

                if (distance < 5)
                {
                    viable = false;
                }
            }

            if (viable)
            {
                break;
            }
        }

        if (!viable)
        {
            Debug.LogError("no possible squad location");
            return;
        }

        // Spawn squad object

        GameObject container = team == 0 ? friendContainer : enemyContainer;
        GameObject prefab    = team == 0 ? FriendlySquadPrefab : EnemySquadPrefab;

        GameObject newSquad = Instantiate(prefab, new Vector3(), new Quaternion(0, 0, 0, 0), container.transform);

        byte[] randomNumbers = new[]
        { (byte)Random.Range(48, 126), (byte)Random.Range(48, 126), (byte)Random.Range(48, 126) };
        newSquad.name = size + " t Squad " + ByteArrayToString(randomNumbers);
        Debug.Log("squad location " + squadLocation);
        newSquad.GetComponent <Squad>().aStar    = aStar.transform;
        newSquad.GetComponent <Squad>().position = squadLocation;

        // Get movementRadius

        float movementRadius = newSquad.GetComponent <Squad>().movementRadiusMultiplier *Mathf.Sqrt(size);

        // Spawn tanks

        for (int t = 0; t < size; t++)
        {
            // 100 tries

            bool       viableT      = true;
            Vector2    tankLocation = new Vector2();
            GameObject tankPrefab   = team == 0 ? FriendlyTankPrefab : EnemyTankPrefab;

            for (int i = 0; i < 100; i++)
            {
                viableT = true;

                // Get relative position

                float relX = Random.Range(-movementRadius, movementRadius);
                float relY = Random.Range(-movementRadius, movementRadius);

                // Check if inside circle

                float magnitude = Mathf.Sqrt(relX * relX + relY * relY);
                if (magnitude > movementRadius)
                {
                    viableT = false;
                    continue;
                }

                tankLocation = squadLocation + new Vector2(relX, relY);

                // Check for walkable terrain

                if (!aStar.GetNearest(tankLocation).node.Walkable)
                {
                    Map.DrawSquare(tankLocation, Color.red, 50f);
                    viableT = false;
                    continue;
                }

                // Check if not too close to another entity

                List <GameObject> nulls = new List <GameObject>();

                foreach (GameObject entity in GameMaster.entities)
                {
                    if (entity == null)
                    {
                        nulls.Add(entity);

                        continue;
                    }

                    float dist = ((Vector2)entity.transform.position - tankLocation).magnitude;

                    if (dist > 10)
                    {
                        continue;
                    }

                    if (dist < tankPrefab.GetComponent <Entity>().obstacleSize +
                        entity.GetComponent <Entity>().obstacleSize)
                    {
                        Map.DrawSquare(tankLocation, Color.yellow, 50f);
                        viableT = false;
                        break;
                    }
                }

                foreach (GameObject entity in nulls)
                {
                    try {
                        GameMaster.friends.Remove(entity);
                    } catch (Exception e) {
                        GameMaster.enemies.Remove(entity);
                    }
                    GameMaster.entities.Remove(entity);
                }

                if (viableT)
                {
                    break;
                }
            }

            if (!viableT)
            {
                Debug.LogError("no possible tank location for squad " + newSquad.transform.name);
                continue;
            }

            // Spawn tank

            GameObject newTank = Instantiate(tankPrefab, tankLocation, new Quaternion(0, 0, 0, 0), newSquad.transform);

            // Set references

            newTank.GetComponent <Moving>().aStar      = aStar.transform;
            newTank.GetComponent <Vehicle>().mapObject = map.transform;
            newTank.GetComponent <Entity>().squad      = newSquad.GetComponent <Squad>();
            newTank.GetComponent <Entity>().hasSquad   = true;

            // Add to GameMaster

            GameMaster.entities.Add(newTank);
            if (team == 0)
            {
                GameMaster.friends.Add(newTank);
            }
            else
            {
                GameMaster.enemies.Add(newTank);
            }
        }

        Squad squadComp = newSquad.GetComponent <Squad>();

        squadComp.targetPosition = squadLocation;
        squadComp.movementMode   = Squad.MovementMode.Stationary;
        squadComp.spawned        = true;
        squadComp.Start();
    }
Example #8
0
    public void FindRandomPlace()
    {
        // 10 tries

        for (int i = 0; i < 10; i++)
        {
            // Create vector with random x and y

            Vector2 random = new Vector2(UnityEngine.Random.Range(-randomMovementDistance, +randomMovementDistance), UnityEngine.Random.Range(-randomMovementDistance, +randomMovementDistance));
            Vector2 newPos = position + random;

            // Check if in map

            if (!Map.IsWithinBounds(newPos))
            {
                continue;
            }

            // Check if still withing movement distance

            float diff = random.magnitude;

            if (diff > randomMovementDistance)
            {
                continue;
            }

            // Check if accessible

            if (!aStarPath.GetNearest(newPos).node.Walkable)
            {
                continue;
            }

            // Check if inside other squad

            bool trespassing = false;
            foreach (Squad squad in LevelMaster.squads)
            {
                if (squad.team != team)
                {
                    continue;
                }

                float dist = (squad.position - newPos).magnitude;
                if (dist < squad.movementRadius || dist < movementRadius)
                {
                    trespassing = true;
                    break;
                }
            }

            if (trespassing)
            {
                continue;
            }

            // Search successful, change target

            targetPosition = newPos;
            movementMode   = MovementMode.Moving;
            hasTarget      = true;

            return;
        }
    }