///Find a path 'from' and 'to', providing a callback for when path is ready containing the path.
    public void FindPath(Vector2 start, Vector2 end, System.Action <List <Vector2> > callback)
    {
        if (CheckLOS(start, end))
        {
            callback(new List <Vector2>(new Vector2[] { start, end }));
            return;
        }

        //make a temp list with all existing nodes cloned
        List <PathNode> tempNodes = new List <PathNode>();

        foreach (var node in nodes)
        {
            tempNodes.Add(node.Clone());
        }

        //create start & end as nodes
        PathNode startNode = new PathNode(start);
        PathNode endNode   = new PathNode(end);

        //add start and end nodes
        tempNodes.Add(startNode);
        tempNodes.Add(endNode);

        //link only those with the rest
        LinkNode(startNode, tempNodes);
        LinkNode(endNode, tempNodes);

        StartCoroutine(AStar.CalculatePath(startNode, endNode, tempNodes, callback));
    }
Beispiel #2
0
    //Pathfind next request
    void TryNextFindPath()
    {
        if (isProcessingPath || pathRequests.Count <= 0)
        {
            return;
        }

        currentRequest   = pathRequests.Dequeue();
        isProcessingPath = true;

        if (!PointIsValid(currentRequest.start))
        {
            currentRequest.start = GetCloserEdgePoint(currentRequest.start);
        }

        //create start & end as temp nodes
        startNode = new PathNode(currentRequest.start);
        endNode   = new PathNode(currentRequest.end);

        nodes.Add(startNode);
        LinkStart(startNode, nodes);

        nodes.Add(endNode);
        LinkEnd(endNode, nodes);

        StartCoroutine(AStar.CalculatePath(startNode, endNode, nodes.ToArray(), RequestDone));
    }
    //
    void FindPath()
    {
        if (null == m_target || !CanControl)
        {
            return;
        }
        AStarMapCell        start = m_astarMap.GetCell(m_data.Row, m_data.Column);
        AStarMapCell        end   = m_astarMap.GetCell(m_target.Row, m_target.Column);
        List <AStarMapCell> list  = AStar.CalculatePath(start, end, m_astarMap);

        if (list.Count > 0)
        {
            m_data.Move(list[0].Column - m_data.Column, list[0].Row - m_data.Row);
            AudioManager.Instance.PlayAudio("dog", true);
        }
        else
        {
            if (m_data.IsLookLeft)
            {
                m_data.Move(-1, 0);
            }
            else
            {
                m_data.Move(1, 0);
            }
            StartCoroutine(RetryFindPath(1));
        }
    }
Beispiel #4
0
    void Start()
    {
        initData();

        gridObjs = new List <GridObj>();

        int[] mapData = GenerateRandomData();

        IO.SaveDataInLocal(mapData);

        int startIndex = 0;
        int destIndex  = 0;

        for (int i = 0; i < mapData.Length; i++)
        {
            if (mapData[i] == (int)GridType.Init)
            {
                startIndex = i;
            }
            if (mapData[i] == (int)GridType.Target)
            {
                destIndex = i;
            }
        }

        GenerateMap(mapData);


        AStar.Init(gridsWidth, gridsHeight);
        path = AStar.CalculatePath(mapData, startIndex, destIndex);
    }
Beispiel #5
0
 private void Update()
 {
     if (aStarActive)
     {
         if (!aStarMoving)
         {
             if (data.snakeList.Count < 1)
             {
                 return;
             }
             //Finds path from snake to fruit. Calculates a new path after every movement
             path        = new List <Vector2Int>(aStar.CalculatePath(data.snakeList[0].position));
             aStarMoving = true;
             //If no path could be made, move up
             if (path.Count < 2)
             {
                 snakeController.SetMoveDirection(Vector2Int.up);
             }
             //Else move according to the first set of vectors that makes up the path
             else
             {
                 snakeController.SetMoveDirection(path[1] - path[0]);
             }
             aStarReady = true;
         }
     }
 }
    private Phase currentPhaseA = Phase.PreSetupA; //start at PreSetUp phase

    public void Setup()
    {
        int startIdxA = (graphA.gridHeight / 2) * graphA.gridWidth;                                                //sets a new int at the start of the graph
        int endIdxA   = startIdxA + graphA.gridWidth - 1;                                                          //sets a new int at the end of the graph

        startTileA = graphA.tilesA[startIdxA];                                                                     //sets startTile to the first tile using startIdx
        endTileA   = graphA.tilesA[endIdxA];                                                                       //sets endTile to the last tile at the end of the graph using endIdx

        Instantiate(spawnPrefabA, startTileA.transform.position, Quaternion.identity);                             //spawns enemy spawner at startTile position
        GameObject defendInstanceA = Instantiate(defendPrefabA, endTileA.transform.position, Quaternion.identity); //spawns base at endTile position

        defendInstanceA.GetComponent <BaseA>().gameStateA = this;

        enemyPathA = graphA.CalculatePath(startTileA, endTileA); //uses CalculatePath function to make its way from enemy spawner to base/makes its way from startTile to endTile(startTile and endTile are used as start and end points)

        currentPhaseA = Phase.BuildA;                            //set current state to build
    }
Beispiel #7
0
    // Update is called once per frame
    void Update()
    {
        if (GameManager.manager.playerStats.isDead)
        {
            return;
        }

        if (mapRect.Contains(Input.mousePosition))
        {
            mousePos = new Vector2Int(Mathf.FloorToInt((Input.mousePosition.x - pointA.position.x) / ((pointB.position.x - pointA.position.x) / DungeonGenerator.dungeonGenerator.mapWidth)), Mathf.FloorToInt((Input.mousePosition.y - (ResolutionManager.resolutionManager._Resolution == ResolutionManager.resolutionType.small ? bigY : smallY)) / ((pointB.position.y - pointA.position.y) / DungeonGenerator.dungeonGenerator.mapHeight))); //14 20

            if (!MapManager.IsValid)
            {
                return;
            }

            if (MapManager.map[mousePos.x, mousePos.y].isExplored)
            {
                Selector.Current.SelectedTile(mousePos.x, mousePos.y);

                if (MapManager.map[mousePos.x, mousePos.y].isWalkable || MapManager.map[mousePos.x, mousePos.y].type == "Door" || MapManager.map[mousePos.x, mousePos.y].enemy != null)
                {
                    _selected = true;
                    path      = null;

                    path = AStar.CalculatePath(MapManager.playerPos, mousePos);

                    foreach (var pathTile in path)
                    {
                        MapManager.map[pathTile.x, pathTile.y].decoy = $"<color=#2B3659>\u205C</color>";
                    }

                    DungeonGenerator.dungeonGenerator.DrawMap(MapManager.map);
                }
                else
                {
                    _selected = false;
                }
            }

            if (_selected && Input.GetMouseButtonDown(0))
            {
                StartCoroutine(WalkPath(path));
            }

            if (Input.GetMouseButtonDown(1))
            {
                if (MapManager.map[mousePos.x, mousePos.y].isVisible && MapManager.map[mousePos.x, mousePos.y].isExplored && MapManager.map[mousePos.x, mousePos.y].enemy != null)
                {
                    GameManager.manager.UpdateMessages($"<color=red>{MapManager.map[mousePos.x, mousePos.y].enemy.GetComponent<RoamingNPC>().enemySO.enemyInfo}</color>");
                }
            }
        }
    }
Beispiel #8
0
    ///Find a path 'from' and 'to', providing a callback for when path is ready containing the path.
    public void FindPath(Vector2 start, Vector2 end, System.Action <List <Vector2> > callback)
    {
        if (CheckLOS(start, end))
        {
            callback(new List <Vector2> {
                start, end
            });
            return;
        }

        //make a temp list with all existing nodes cloned
        var tempNodes = new List <PathNode>();

        foreach (var node in nodes)
        {
            tempNodes.Add(node.Clone());
        }

        var originalStart = start;

        if (!PointIsValid(start))
        {
            start = GetCloserEdgePoint(start);
        }

        //create start & end as nodes
        var startNode = new PathNode(start);
        var endNode   = new PathNode(end);

        //add start and end nodes
        tempNodes.Add(startNode);
        tempNodes.Add(endNode);

        //link only those with the rest
        LinkNode(startNode, tempNodes);
        LinkNode(endNode, tempNodes);


        StartCoroutine(AStar.CalculatePath(startNode, endNode, tempNodes, delegate(List <Vector2> path){
            path.Insert(0, originalStart);
            callback(path);
        }));
    }
    void OnTileClicked(SpriteTile sender)
    {
        if (_currentTile != null)
        {
            if (sender == _currentTile)
            {
                // Deselect if we click the same tile again
                SetCurrentTile(null);
            }
            else if (sender.Matches(_currentTile))
            {
                int turns = int.MaxValue;

                // Temporarily set the target node to be walkable before pathfinding since AStar needs to be able to walk onto the node to find it.
                float oldWeight = sender.gridNode.pathfindingWeight;
                sender.gridNode.pathfindingWeight = 1;
                IAStarNode[] path = AStar.CalculatePath(_currentTile.gridNode, sender.gridNode, out turns);
                sender.gridNode.pathfindingWeight = oldWeight;

                if (turns <= GameSettings.maxPathfindingTurns)
                {
                    // If it's a valid match spawn a MatchAnimation and play it
                    _currentTile.gameObject.AddComponent <MatchAnimation>().Play(_currentTile, sender, path);
                    SetCurrentTile(null);
                }
                else
                {
                    // If the path has too many turns simply select the tile instead
                    SetCurrentTile(sender);
                }
            }
            else
            {
                // Tile's don't match, select the new one
                SetCurrentTile(sender);
            }
        }
        else
        {
            // We don't have a selected tile yet, select the new one
            SetCurrentTile(sender);
        }
    }
Beispiel #10
0
	// Update is called once per frame
	void Update()
	{
		if (selected != null)
		{
			if (Input.GetMouseButtonDown(1))
			{
				if (!walking)
					currentCell = GetCurrentCell().coord;
			}
			if (Input.GetMouseButton(1))
			{
				if (!walking)
				{
					oldDest = dest;
					dest = mouseHandler.FindCell();
					if (dest != null && !dest.Equals(oldDest))
					{
						path = astar.CalculatePath(currentCell, dest.coord);
					}
					for (int i = 0; i < path.Count; i++)
					{
						if (i <= shortRange)
							hexes[path[i].coord].GetComponent<MeshRenderer>().material.color = shortColor;
						if (i > shortRange && i <= mediumRange)
							hexes[path[i].coord].GetComponent<MeshRenderer>().material.color = mediumColor;
						if (i > mediumRange)
							hexes[path[i].coord].GetComponent<MeshRenderer>().material.color = farColor;
					}
				}
			}

			if (Input.GetMouseButtonUp(1))
			{
				if (!walking && dest != null)
					StartCoroutine(Walk());
				astar.resetPath();
				temp++;

			}
		}
	}
Beispiel #11
0
    ///Find a path 'from' and 'to', providing a callback for when path is ready containing the path.
    public void FindPath(Vector2 start, Vector2 end, System.Action <List <Vector2> > callback)
    {
        if (CheckLOS(start, end))
        {
            callback(new List <Vector2> {
                start, end
            });
            return;
        }

        //make a temp list with all existing nodes cloned
        tempNodes = new PathNode[nodes.Count + 2];
        for (int i = 0; i < nodes.Count; i++)
        {
            tempNodes[i] = nodes[i].Clone();
        }

        if (!PointIsValid(start))
        {
            start = GetCloserEdgePoint(start);
        }

        //create start & end as nodes
        var startNode = new PathNode(start);
        var endNode   = new PathNode(end);

        //add start and end nodes
        tempNodes[tempNodes.Length - 2] = startNode;
        tempNodes[tempNodes.Length - 1] = endNode;

        //link only those with the rest
        LinkNode(startNode, tempNodes);
        LinkNode(endNode, tempNodes);

        StartCoroutine(AStar.CalculatePath(startNode, endNode, tempNodes, callback));
    }
    public override void Calculate(RoamingNPC t)
    {
        if (t.rootDuration > 0)
        {
            t.rootDuration--;
        }
        else if (t.rooted)
        {
            t.rooted = false;
        }

        if (t.enemySO._Behaviour != EnemiesScriptableObject.E_behaviour.npc)
        {
            if (t.sleeping)
            {
                int distance = Mathf.Max(Mathf.Abs(PlayerMovement.playerMovement.position.x - t.__position.x), Mathf.Abs(PlayerMovement.playerMovement.position.y - t.__position.y));
                if (distance < 7)
                {
                    t.sleeping = false;
                }
                else
                {
                    //Debug.Log("I am sleeping");
                    return;
                }
            }


            if (!t.gameObject.transform.parent.gameObject.activeSelf)
            {
                return;
            }

            t.TriggerEffectTasks();

            bool searchEnemy = true;

            if (t.Board.ContainsKey("Target"))
            {
                if (t.Board["Target"] != null && t.Board["Target"] is RoamingNPC)
                {
                    //Debug.Log("Has Target");
                    RoamingNPC testNPC = (RoamingNPC)t.Board["Target"];
                    if ((testNPC == null) || Vector2Int.Distance(PlayerMovement.playerMovement.position, testNPC.__position) > 5 || testNPC.gameObject == null)
                    {
                        t.Board["Target"] = null;
                    }
                    else
                    {
                        searchEnemy = false;
                    }
                }
            }
            if (searchEnemy)
            {
                //Debug.Log("Has to search enemy");
                Vector2Int enemyPos = new Vector2Int(-100, -100);
                float      minDis   = 10000;
                bool       found    = false;
                foreach (Vector2Int pos in FoV.GetEnemyFoV(t.__position))
                {
                    try
                    {
                        int dis = Mathf.Max(Mathf.Abs(PlayerMovement.playerMovement.position.x - pos.x), Mathf.Abs(PlayerMovement.playerMovement.position.y - pos.y));
                        if (MapManager.map[pos.x, pos.y].enemy != null &&
                            MapManager.map[pos.x, pos.y].enemy != t.gameObject &&
                            MapManager.map[pos.x, pos.y].enemy.GetComponent <RoamingNPC>().enemySO.MyTurnAI != t.enemySO.MyTurnAI &&
                            dis <= 4)
                        {
                            if (dis < minDis)
                            {
                                minDis   = dis;
                                enemyPos = pos;
                                found    = true;
                            }
                        }
                    }
                    catch { }
                }

                if (found)
                {
                    //Debug.Log("Found enemy");
                    t.Board["Target"] = MapManager.map[enemyPos.x, enemyPos.y].enemy.GetComponent <RoamingNPC>();
                }
            }
            if (t.Board.ContainsKey("Target"))
            {
                //Debug.Log("Has enemy missing: " + (t.Board["Target"] == null));
            }
            if (t.Board.ContainsKey("Target") && t.Board["Target"] != null && t.Board["Target"] is RoamingNPC npc)
            {
                //Debug.Log("Target aquired");

                int distance = Mathf.Max(Mathf.Abs(npc.__position.x - t.__position.x), Mathf.Abs(npc.__position.y - t.__position.y));
                // move to target and attack

                var att = GetAttack(t);
                if (att.InRange(t.__position, npc.pos))
                {
                    att.Calculate((t, npc));
                    return;
                }
                else
                {
                    t.path = null;
                    t.path = AStar.CalculatePath(t.__position, npc.__position);
                    Debug.Log(t.path.Count);
                    if (!(PlayerMovement.playerMovement.position == t.path[0] || PlayerMovement.playerMovement.position == t.path[1]))
                    {
                        // Debug.Log("Move to enemy");
                        t.MoveTo(t.path[0].x, t.path[0].y);
                        return;
                    }
                }
            }


            // move to player
            // check if next to player
            int pDistance = Mathf.Max(Mathf.Abs(PlayerMovement.playerMovement.position.x - t.__position.x), Mathf.Abs(PlayerMovement.playerMovement.position.y - t.__position.y));


            //Debug.Log(pDistance);
            if (pDistance == 1)
            {
                // we are too close
                Vector2Int diff = t.__position - PlayerMovement.playerMovement.position;

                // we move away from the player
                if (MapUtility.IsMoveable(t.__position.x + diff.x, t.__position.y + diff.y))
                {
                    t.MoveTo(t.__position.x + diff.x, t.__position.y + diff.y);
                }
                else
                {
                    // find another way
                    Vector2Int[] alternatives = MapUtility.Box1
                                                .Copy()
                                                .Check((pos) => MapUtility.IsMoveable(pos) && MapUtility.MoveDistance(pos, PlayerMovement.playerMovement.position) == 2);
                    if (alternatives.Length > 0)
                    {
                        Vector2Int target = alternatives.GetRandom();
                        t.MoveTo(target.x, target.y);
                    }
                }
            }
            else
            {
                // check how far away
                // if far away follow
                if (pDistance > 2)
                {
                    t.path = null;
                    //Debug.Log("Follow");
                    t.path = AStar.CalculatePath(t.__position, PlayerMovement.playerMovement.position);
                    //Debug.Log(t.path.Count);
                    t.MoveTo(t.path[0].x, t.path[0].y);
                }
                else
                {
                    // else go random
                    Vector2Int[] alternatives = MapUtility.Box1
                                                .Copy().Combine(MapUtility.Origin.Copy())
                                                .MoveCenter(t.__position)
                                                .Check((pos) => MapUtility.IsMoveable(pos) && MapUtility.MoveDistance(pos, PlayerMovement.playerMovement.position) > 1);
                    if (alternatives.Length > 0)
                    {
                        Vector2Int target = alternatives.GetRandom();
                        t.MoveTo(target.x, target.y);
                    }
                }
            }
        }
    }
    public override void Calculate(RoamingNPC t)
    {
        if (t.rootDuration > 0)
        {
            t.rootDuration--;
        }
        else if (t.rooted)
        {
            t.rooted = false;
        }

        //t.playerDetected = false;

        if (t.enemySO._Behaviour != EnemiesScriptableObject.E_behaviour.npc)
        {
            if (t.sleeping)
            {
                return;
            }

            if (!t.gameObject.transform.parent.gameObject.activeSelf)
            {
                return;
            }

            t.TriggerEffectTasks();
            if (t.CurrentTarget != null && t.CurrentTarget.currHp == 0)
            {
                t.CurrentTarget = null;
            }

            // check for out of sight enemy
            if (!(t.CurrentTarget == null))
            {
                if (!FoV.InLineOfSight(t.pos, t.CurrentTarget.pos))
                {
                    // out of sight out of mind i guess
                    t.LastKnownTargetPos = t.CurrentTarget.pos;

                    t.CurrentTarget = null;
                    // TODO: make enemy run to last known position
                }
            }


            // check if current target is still valid
            if (!(t.CurrentTarget == null))
            {
                // we are targeting something
                // range here
                if (MapUtility.MoveDistance(t.pos, t.CurrentTarget.pos) == 1)
                {
                    // the target is in attackrange so we dont change anything
                }
                else
                {
                    // target may be running away. we are looking at other potential targets that are near us
                    if (t.RetailiationList.Count > 0)
                    {
                        // we have recently been attacked by somebody
                        var alt = t.RetailiationList.ToArray().Check((u) => MapUtility.MoveDistance(u.pos, t.pos) == 1);
                        if (alt.Length > 0)
                        {
                            t.CurrentTarget = alt.GetRandom();
                        }
                    }
                }
            }
            else
            {
                // look for possible target
                var view = FoV.GetEnemyFoV(t.__position).ToArray().Check((p) => MapManager.map[p.x, p.y].hasPlayer || MapManager.map[p.x, p.y].enemy != null);

                if (view.Length > 0)
                {
                    List <IUnit> possibleTargets = new List <IUnit>();

                    IUnit nt = null;


                    foreach (var pos in view)
                    {
                        if (MapManager.map[pos.x, pos.y].enemy != null && MapManager.map[pos.x, pos.y].enemy.GetComponent <RoamingNPC>().enemySO.MyTurnAI is HelperTurnBehaviour)
                        {
                            // we found a doggo to attack
                            if (nt == null)
                            {
                                nt = MapManager.map[pos.x, pos.y].enemy.GetComponent <RoamingNPC>();
                                t.LastKnownTargetPos = nt.pos;
                            }
                            else
                            {
                                if (MapUtility.MoveDistance(t.pos, nt.pos) > MapUtility.MoveDistance(t.pos, pos))
                                {
                                    nt = MapManager.map[pos.x, pos.y].enemy.GetComponent <RoamingNPC>();
                                    t.LastKnownTargetPos = nt.pos;
                                }
                            }
                        }
                        if (MapManager.map[pos.x, pos.y].hasPlayer)
                        {
                            if (nt == null && !GameManager.manager.playerStats.isInvisible)
                            {
                                if (t.enemySO.canSpeak)
                                {
                                    int r = Random.Range(1, 4);
                                    if (r == 1)
                                    {
                                        GameManager.manager.UpdateMessages($"<b>{GameManager.manager.monsterDetectPlayer[Random.Range(0, GameManager.manager.monsterDetectPlayer.Count)]}</b> " + $"said <color=#{t.enemySO.E_color}>{t.enemySO.E_name}</color> in a terrifying voice.");
                                    }
                                    else if (r == 2)
                                    {
                                        GameManager.manager.UpdateMessages($"<color=#{t.enemySO.E_color}>{t.enemySO.E_name}</color> makes incomprehensible sounds.");
                                    }
                                    else if (r == 3)
                                    {
                                        GameManager.manager.UpdateMessages($"When <color=#{t.enemySO.E_color}>{t.enemySO.E_name}</color> noticed you it started screaming and moaning terribly.");
                                    }
                                }

                                nt = t.playerStats;
                                try { t.LastKnownTargetPos = nt.pos; } catch { }
                            }
                            else
                            {
                                if (MapUtility.MoveDistance(t.pos, nt.pos) > MapUtility.MoveDistance(t.pos, pos))
                                {
                                    nt = t.playerStats;
                                    t.LastKnownTargetPos = nt.pos;
                                }
                            }
                        }
                    }
                    if (nt != null)
                    {
                        // found the closest possible target:
                        t.CurrentTarget      = nt;
                        t.LastKnownTargetPos = nt.pos;
                    }
                }
            }

            switch (t.enemySO._Behaviour)
            {
            case EnemiesScriptableObject.E_behaviour.cowardly:
                if (t.__currentHp <= (t.maxHp / 2) && (int)Random.Range(0, 2) == 1 && t.runCounter > 0 || (t.runCounter > 0 && t.runCounter < 5))     //RUN FROM PLAYER
                {
                    t.runDirection = t.__position - MapManager.playerPos;

                    Vector2Int runCell = t.__position + t.runDirection;

                    t.runCounter--;

                    t.path = null;

                    t.path = AStar.CalculatePath(t.__position, runCell);

                    t.MoveTo(t.path[0].x, t.path[0].y);
                    return;
                }
                else
                {
                    t.runCounter = 5;
                }
                break;

            case EnemiesScriptableObject.E_behaviour.recovers:
                if (t.__currentHp <= (t.maxHp / 2) && t.hpRegenCooldown == 0)
                {
                    t.hpRegenCooldown--;
                    t.__currentHp += Mathf.FloorToInt(t.maxHp * .25f);
                    return;
                }
                else if (t.hpRegenCooldown < 10 && t.hpRegenCooldown > 0)
                {
                    t.hpRegenCooldown--;
                }
                break;
            }

            if (t.CurrentTarget != null)
            {
                var att = GetAttack(t);
                if (att.InRange(t.__position, t.CurrentTarget.pos))
                {
                    att.Calculate((t, t.CurrentTarget));
                    return;
                }

                /*
                 * if (new Vector2Int(t.__position.x - 1, t.__position.y) == MapManager.playerPos)
                 * {
                 *  GetAttack(t).Attack(t, t.playerStats);
                 *  return;
                 * }
                 * else if (new Vector2Int(t.__position.x + 1, t.__position.y) == MapManager.playerPos)
                 * {
                 *  GetAttack(t).Attack(t, t.playerStats);
                 *  return;
                 * }
                 * else if (new Vector2Int(t.__position.x, t.__position.y - 1) == MapManager.playerPos)
                 * {
                 *  GetAttack(t).Attack(t, t.playerStats);
                 *  return;
                 * }
                 * else if (new Vector2Int(t.__position.x, t.__position.y + 1) == MapManager.playerPos)
                 * {
                 *  GetAttack(t).Attack(t, t.playerStats);
                 *  return;
                 * }
                 * else if (new Vector2Int(t.__position.x - 1, t.__position.y - 1) == MapManager.playerPos)
                 * {
                 *  GetAttack(t).Attack(t, t.playerStats);
                 *  return;
                 * }
                 * else if (new Vector2Int(t.__position.x + 1, t.__position.y - 1) == MapManager.playerPos)
                 * {
                 *  GetAttack(t).Attack(t, t.playerStats);
                 *  return;
                 * }
                 * else if (new Vector2Int(t.__position.x - 1, t.__position.y + 1) == MapManager.playerPos)
                 * {
                 *  GetAttack(t).Attack(t, t.playerStats);
                 *  return;
                 * }
                 * else if (new Vector2Int(t.__position.x + 1, t.__position.y + 1) == MapManager.playerPos)
                 * {
                 *  GetAttack(t).Attack(t, t.playerStats);
                 *  return;
                 * }
                 */

                t.path = null;

                t.path = AStar.CalculatePath(t.__position, t.CurrentTarget.pos);

                t.MoveTo(t.path[0].x, t.path[0].y);
            }
            else
            {
                if (t._x > 0)
                {
                    t._x--;

                    t.path = null;

                    t.path = AStar.CalculatePath(t.__position, MapManager.playerPos);

                    t.MoveTo(t.path[0].x, t.path[0].y);
                }
                else
                {
                    t.MoveTo(t.__position.x + Random.Range(-1, 2), t.__position.y + Random.Range(-1, 2)); //move to random direction
                }
            }
        }
        else
        {
            if (!t.gameObject.transform.parent.gameObject.activeSelf)
            {
                return;
            }

            if (t.enemySO.finishedDialogue)
            {
                t.MoveTo(t.__position.x + (int)Random.Range(-1, 2), t.__position.y + (int)Random.Range(-1, 2)); //move to random direction
            }
        }
    }
Beispiel #14
0
    public static void Chase(EnemyBrain brain, Vector2Int playerPosition)
    {
        List <Vector2Int> path = AStar.CalculatePath(brain.position, playerPosition);

        EnemyMovement.Move(path[0], brain);
    }
    public override void Calculate(RoamingNPC t)
    {
        if (t.rootDuration > 0)
        {
            t.rootDuration--;
        }
        else if (t.rooted)
        {
            t.rooted = false;
        }

        //t.playerDetected = false;

        if (t.sleeping)
        {
            return;
        }

        if (!t.gameObject.transform.parent.gameObject.activeSelf)
        {
            return;
        }

        t.TriggerEffectTasks();
        if (t.CurrentTarget != null && t.CurrentTarget.currHp == 0)
        {
            t.CurrentTarget = null;
        }

        // check for out of sight enemy
        if (!(t.CurrentTarget == null))
        {
            if (!FoV.InLineOfSight(t.pos, t.CurrentTarget.pos))
            {
                // out of sight out of mind i guess
                t.LastKnownTargetPos = t.CurrentTarget.pos;

                t.CurrentTarget = null;
                // TODO: make enemy run to last known position
            }
        }


        // check if current target is still valid
        if (!(t.CurrentTarget == null))
        {
            // we are targeting something
            // range here
            if (MapUtility.MoveDistance(t.pos, t.CurrentTarget.pos) == 1)
            {
                // the target is in attackrange so we dont change anything
            }
            else
            {
                // target may be running away. we are looking at other potential targets that are near us
                if (t.RetailiationList.Count > 0)
                {
                    // we have recently been attacked by somebody
                    var alt = t.RetailiationList.ToArray().Check((u) => MapUtility.MoveDistance(u.pos, t.pos) == 1);
                    if (alt.Length > 0)
                    {
                        t.CurrentTarget = alt.GetRandom();
                    }
                }
            }
        }
        else
        {
            // look for possible target
            var view = FoV.GetEnemyFoV(t.__position).ToArray().Check((p) => MapManager.map[p.x, p.y].hasPlayer || MapManager.map[p.x, p.y].enemy != null);

            if (view.Length > 0)
            {
                List <IUnit> possibleTargets = new List <IUnit>();

                IUnit nt = null;


                foreach (var pos in view)
                {
                    if (MapManager.map[pos.x, pos.y].enemy != null && MapManager.map[pos.x, pos.y].enemy.GetComponent <RoamingNPC>().enemySO.MyTurnAI is HelperTurnBehaviour)
                    {
                        // we found a doggo to attack
                        if (nt == null)
                        {
                            nt = MapManager.map[pos.x, pos.y].enemy.GetComponent <RoamingNPC>();
                            t.LastKnownTargetPos = nt.pos;
                        }
                        else
                        {
                            if (MapUtility.MoveDistance(t.pos, nt.pos) > MapUtility.MoveDistance(t.pos, pos))
                            {
                                nt = MapManager.map[pos.x, pos.y].enemy.GetComponent <RoamingNPC>();
                                t.LastKnownTargetPos = nt.pos;
                            }
                        }
                    }
                    if (MapManager.map[pos.x, pos.y].hasPlayer)
                    {
                        if (nt == null)
                        {
                            nt = t.playerStats;
                            t.LastKnownTargetPos = nt.pos;
                        }
                        else
                        {
                            if (MapUtility.MoveDistance(t.pos, nt.pos) > MapUtility.MoveDistance(t.pos, pos))
                            {
                                nt = t.playerStats;
                                t.LastKnownTargetPos = nt.pos;
                            }
                        }
                    }
                }
                if (nt != null)
                {
                    // found the closest possible target:
                    t.CurrentTarget      = nt;
                    t.LastKnownTargetPos = nt.pos;
                }
            }
        }

        if (t.CurrentTarget != null)
        {
            var att = GetAttack(t);
            if (att.BlobInRange(t.__position, t.CurrentTarget.pos))
            {
                att.Calculate((t, t.CurrentTarget));
                return;
            }

            t.path = null;

            t.path = AStar.CalculatePath(t.__position, t.CurrentTarget.pos);

            BlobMoveTo(t, t.path[0].x, t.path[0].y);
        }
        else
        {
            if (t._x > 0)
            {
                t._x--;

                t.path = null;

                t.path = AStar.CalculatePath(t.__position, MapManager.playerPos);

                BlobMoveTo(t, t.path[0].x, t.path[0].y);
            }
            else
            {
                //BlobMoveTo(t, t.__position.x + Random.Range(-1, 2), t.__position.y + Random.Range(-1, 2)); //move to random direction
            }
        }
    }
Beispiel #16
0
 // Use this for initialization
 void Start()
 {
     map = AStarMapStream.Read(Application.dataPath + "/scene1.txt");
     map.CalculateCellPosition(new Vector2(2.56f, 2.56f), Vector2.zero);
     path = AStar.CalculatePath(map.GetCell(0, 0), map.GetCell(map.Row - 1, map.Column - 1), map);
 }
Beispiel #17
0
    private IEnumerator GenerateCaves()
    {
        string[] lines = new string[generateAmount + 1];
        lines[0] = generateAmount + "";
        for (int i = 0; i < generateAmount; i++)
        {
            algorithm.ClearCave();
            // SPEED PARAMTER
            float        startTime  = Time.realtimeSinceStartup;
            CaveCell[][] cave       = algorithm.GenerateCave();
            int          caveWidth  = cave.Length;
            int          caveHeight = cave[0].Length;
            float        seconds    = Time.realtimeSinceStartup - startTime;
            string       line       = seconds + "|";
            percent = (i + (1f / 3f)) / (float)generateAmount;
            yield return(new WaitForEndOfFrame());

            // DIVERSITY PARAMTER
            int groundFloors   = 0;
            int wallFloors     = 0;
            int corridorFloors = 0;
            int cornerFloors   = 0;
            int deadEndFloor   = 0;
            for (int centerX = 0; centerX < caveWidth; centerX++)
            {
                for (int centerY = 0; centerY < caveHeight; centerY++)
                {
                    if (cave[centerX][centerY].type == CaveCellType.Ground)
                    {
                        int wallsCount = 0;
                        // Top Neighbour
                        bool topFloor = false;
                        if (IsOnGrid(cave, centerX, centerY + 1))
                        {
                            if (cave[centerX][centerY + 1].type == CaveCellType.Wall)
                            {
                                wallsCount++; topFloor = true;
                            }
                        }
                        else
                        {
                            wallsCount++; topFloor = true;
                        }

                        // Right Neighbour
                        bool rightFloor = false;
                        if (IsOnGrid(cave, centerX + 1, centerY))
                        {
                            if (cave[centerX + 1][centerY].type == CaveCellType.Wall)
                            {
                                wallsCount++; rightFloor = true;
                            }
                        }
                        else
                        {
                            wallsCount++; rightFloor = true;
                        }

                        // Bottom Neighbour
                        bool bottomFloor = false;
                        if (IsOnGrid(cave, centerX, centerY - 1))
                        {
                            if (cave[centerX][centerY - 1].type == CaveCellType.Wall)
                            {
                                wallsCount++; bottomFloor = true;
                            }
                        }
                        else
                        {
                            wallsCount++; bottomFloor = true;
                        }

                        // Left Neighbour
                        bool leftFloor = false;
                        if (IsOnGrid(cave, centerX - 1, centerY))
                        {
                            if (cave[centerX - 1][centerY].type == CaveCellType.Wall)
                            {
                                wallsCount++; leftFloor = true;
                            }
                        }
                        else
                        {
                            wallsCount++; leftFloor = true;
                        }

                        if (wallsCount == 0)
                        {
                            groundFloors++;
                        }
                        else if (wallsCount == 1)
                        {
                            wallFloors++;
                        }
                        else if (wallsCount == 2)
                        {
                            if (topFloor && bottomFloor && !rightFloor && !leftFloor ||
                                !topFloor && !bottomFloor && rightFloor && leftFloor)
                            {
                                corridorFloors++;
                            }
                            else
                            {
                                cornerFloors++;
                            }
                        }
                        else if (wallsCount == 3)
                        {
                            deadEndFloor++;
                        }
                    }
                }
            }
            line   += groundFloors + "|" + wallFloors + "|" + corridorFloors + "|" + cornerFloors + "|" + deadEndFloor + "|";
            percent = (i + (2f / 3f)) / (float)generateAmount;
            yield return(new WaitForEndOfFrame());

            // COMPLEXITY PARAMTER
            List <CaveCell> groundCells = new List <CaveCell>();
            for (int x = 0; x < caveWidth; x++)
            {
                for (int y = 0; y < caveHeight; y++)
                {
                    if (cave[x][y].type == CaveCellType.Ground)
                    {
                        groundCells.Add(cave[x][y]);
                    }
                }
            }

            float sum = 0;
            for (int j = 0; j < 100; j++)
            {
                CaveCell randomStart = groundCells[UnityEngine.Random.Range(0, groundCells.Count)];
                CaveCell randomEnd   = groundCells[UnityEngine.Random.Range(0, groundCells.Count)];
                if (randomStart == randomEnd)
                {
                    j--;
                    continue;
                }
                float pathValue = AStar.CalculatePath(cave, caveWidth, caveHeight, randomStart.x, randomStart.y, randomEnd.x, randomEnd.y) / 10f;
                if (pathValue != -1)
                {
                    sum += pathValue;
                }
                else
                {
                    j--;
                    continue;
                }
            }
            float media = sum / 100f;
            line += media + "";

            lines[i + 1] = line;
            percent      = (float)(i + 1) / (float)generateAmount;
            yield return(new WaitForEndOfFrame());
        }
        System.IO.File.WriteAllLines(@"C:\Users\GousenPride\Desktop\" + algorithm.GetType().ToString() + ".txt", lines);
    }