Exemple #1
0
    public void GenerateWayPoint()
    {
        Queue <WayPoint> wayPointQueue = new Queue <WayPoint>();

        Vector2Int[] nextKeys = new Vector2Int[4];
        Vector2      nextPosition;
        WayPoint     nextWayPoint;

        Vector2    curPosition = m_centerPosition;
        Vector2Int curKey      = m_centerKey;
        WayPoint   curWayPoint = new WayPoint(curKey);
        Collider2D obstacle    = Physics2D.OverlapBox(curPosition, m_gapSize, 0.0f, m_obstacleLayer);

        if (obstacle == null)
        {
            m_wayPointManager.AddWayPoint(curWayPoint);
        }
        wayPointQueue.Enqueue(curWayPoint);

        // BFS Algorithm
        while (wayPointQueue.Count != 0)
        {
            curWayPoint = wayPointQueue.Dequeue();
            curKey      = curWayPoint.Key;
            // Keys of Right, Up, Left, Down Side
            nextKeys[0] = new Vector2Int(curKey.x + 1, curKey.y);
            nextKeys[1] = new Vector2Int(curKey.x, curKey.y + 1);
            nextKeys[2] = new Vector2Int(curKey.x - 1, curKey.y);
            nextKeys[3] = new Vector2Int(curKey.x, curKey.y - 1);

            for (int i = 0; i < 4; i++)
            {
                // if nextKeys were not out of boundary
                if (((nextKeys[i].x >= m_leftDownKey.x && nextKeys[i].y >= m_leftDownKey.y) &&
                     (nextKeys[i].x <= m_rightUpKey.x && nextKeys[i].y <= m_rightUpKey.y)))
                {
                    nextPosition = m_wayPointManager.ConvertKeyToPosition(nextKeys[i]);
                    obstacle     = Physics2D.OverlapBox(nextPosition, m_gapSize, 0.0f, m_obstacleLayer);
                    if (obstacle == null)
                    {
                        nextWayPoint = new WayPoint(nextKeys[i]);
                        Vector2 position = m_wayPointManager.ConvertKeyToPosition(nextKeys[i]);
                        if (m_wayPointManager.AddWayPoint(nextWayPoint))
                        {
                            wayPointQueue.Enqueue(nextWayPoint);
                        }
                    }
                }
            }
        }
    }