Exemple #1
0
        public void Init()
        {
            // Set the initial settings for the map like Size and Seed
            SetSettings();

            // The ground is set dynamically depending on the map and node size
            SetGround();

            // Generate the grid
            var map = _mazeGenerator.Init();

            _map        = map;
            _newCurrent = _map[0, 0];

            // Position the player on the map
            GameManager.Instance.Load();

            // Create the graph we need for A*
            GetComponentInChildren <Grid>().Init();

            EnableCulling();

            _weatherManager.Init();

            _offset = 12 * GameManager.Instance.Size / 2 - 6;
        }
Exemple #2
0
        public bool Init(float width, float height, float gridSize, float safeExpand)
        {
            mWidth       = width;
            mHeight      = height;
            mGridSize    = gridSize;
            mRecGridSize = 1.0f / gridSize;


            mColCount    = (int)Math.Ceiling(width * mRecGridSize);
            mRowCount    = (int)Math.Ceiling(height * mRecGridSize);
            mExpandCount = (int)Math.Ceiling(safeExpand * mRecGridSize);
            mNodes       = new GridNode[mColCount + mExpandCount * 2, mRowCount + mExpandCount * 2];
            GridNode empty = new GridNode();

            for (int x = 0; x < mColCount + mExpandCount * 2; ++x)
            {
                for (int y = 0; y < mRowCount + mExpandCount * 2; ++y)
                {
                    if (x < mExpandCount || x >= mColCount + mExpandCount || y < mExpandCount || y >= mRowCount + mExpandCount)
                    {
                        mNodes[x, y] = empty;
                    }
                    else
                    {
                        mNodes[x, y] = new GridNode();
                    }
                }
            }
            return(true);
        }
Exemple #3
0
    public Grid(int[,] terrainMap, int player1X, int player1Y, int player2X, int player2Y)
    {
        grid     = new GridNode[10, 10];
        gridSize = 10;

        this.player1X = player1X;
        this.player1Y = player1Y;
        this.player2X = player2X;
        this.player2Y = player2Y;

        int mappedX = 0;
        int mappedY = gridSize - 1;

        for (int i = 0; i < gridSize; i++)
        {
            mappedY = gridSize - 1;
            for (int j = 0; j < gridSize; j++)
            {
                grid[i, j] = new GridNode(i, j, terrainMap[mappedY, mappedX]);

                if (player1X == i && player1Y == j)
                {
                    grid[i, j].player1OnNode = true;
                }

                if (player2X == i && player2Y == j)
                {
                    grid[i, j].player2OnNode = true;
                }

                mappedY--;
            }
            mappedX++;
        }
    }
Exemple #4
0
        void CreateGrid()
        {
            grid = new GridNode[gridSizeX, gridSizeY];
            Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 - Vector3.forward * gridWorldSize.y / 2;

            for (int x = 0; x < gridSizeX; x++)
            {
                for (int y = 0; y < gridSizeY; y++)
                {
                    Vector3 worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.forward * (y * nodeDiameter + nodeRadius);
                    bool    walkable   = !(Physics.CheckSphere(worldPoint, nodeRadius, unwalkableMask));

                    int movementPenalty = 0;


                    Ray        ray = new Ray(worldPoint + Vector3.up * 50, Vector3.down);
                    RaycastHit hit;
                    if (Physics.Raycast(ray, out hit, 100, walkableMask))
                    {
                        walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out movementPenalty);
                    }

                    if (!walkable)
                    {
                        movementPenalty += obstacleProximityPenalty;
                    }


                    grid[x, y] = new GridNode(walkable, worldPoint, x, y, movementPenalty);
                }
            }

            BlurPenaltyMap(3);
        }
Exemple #5
0
        void InitGrid(int[,] mazeData, float _gridSizeX, float _gridSizeY, Vector3 _worldGridBootomLeft, bool showGizmos = false, TerrainType[] _walkableRegions = null)
        {
            gridSizeX = _gridSizeX;
            gridSizeY = _gridSizeY;
            gridHalfY = gridSizeY / 2;
            gridHalfX = gridSizeX * .5f;

            rMax = mazeData.GetUpperBound(0) + 1;
            cMax = mazeData.GetUpperBound(1) + 1;
            if (rMax == 1)
            {
                Debug.LogError("Please generate the mesh first");
                return;
            }
            grids = new GridNode[rMax, cMax];

            worldGridBootomLeft = _worldGridBootomLeft;
            displayGridGizmos   = showGizmos;

            if (_walkableRegions != null)
            {
                walkableRegions = _walkableRegions;


                foreach (var terrian in walkableRegions)
                {
                    walkableLayer |= terrian.terrianLayerMask;
                    walkableDictionary.Add((int)Mathf.Log(terrian.terrianLayerMask.value, 2), terrian.terrianPenality);
                }
            }
        }
Exemple #6
0
    // Use this for initialization
    protected void createGrid(MeshRenderer f)
    {
        // get the mesh renderer to calculate the floor bounds
        floor = f;
        floor_width = floor.bounds.size.x;
        floor_depth = floor.bounds.size.z;

        // init grid array
        grid = new GridNode[blockRows, blockColumns];

        // calculate the block width & depth
        block_width = floor_width / blockRows;
        block_depth = floor_depth / blockColumns;

        // get the top left point to draw from
        Vector3 TopLeftPoint = new Vector3(transform.position.x - (floor_width/2), transform.position.y, transform.position.z + (floor_depth / 2));

        // the current position of the new block in the loop
        Vector3 currentPosition = TopLeftPoint;

        // loop through to add the blocks (nodes) to the grid
        for (int i = 0; i < blockRows; i++)
        {
            for (int j = 0; j < blockColumns; j++)
            {
                grid[i, j] = new GridNode(currentPosition, new Vector2(block_width, block_depth)); // add a node at the current position
                currentPosition.x += block_width; // move to the right one block
            }
            // move to the next row
            currentPosition.x = TopLeftPoint.x;
            currentPosition.z -= block_depth;
        }
    }
Exemple #7
0
 public override void Update(object gameTime)
 {
     if (grid == null)
     {
         grid = GameWorld.FindByType <GridPlane>()[0].grid;
     }
 }
Exemple #8
0
    /// <summary>
    /// Create a new grid and see which tiles that are walkable
    /// </summary>
    public void CreateGrid()
    {
        int width  = GameController.Instance.Width;
        int height = GameController.Instance.Height;

        // Create a new GridNode two dimensional array
        grid = new GridNode[width + 1, height + 1];
        // Get the bottom left position while keeping the middle of the
        // grid at 0,0,0 in the world position
        Vector2 start = new Vector2(-width / 2, -height / 2);

        // Loop through every position in the grid.
        for (int x = 0; x < width + 1; x++)
        {
            for (int y = 0; y < height + 1; y++)
            {
                // Get the world position
                Vector2 worldPosition = new Vector2(start.x + x, start.y + y);

                // See if we collide with anything, because if we do then it's not walkable
                bool walkable = Physics2D.Raycast(worldPosition, Vector2.zero, 1, unwalkableLayers).collider == null;

                // Create a new gridnode passing in walkable, worldposition, grid x and grid y
                grid[x, y] = new GridNode(walkable, worldPosition, x, y);
            }
        }
    }
Exemple #9
0
    void CreateGrid()
    {
        grid = new GridNode[numGridRows, numGridCols];
        Vector3 worldBottomLeft = transform.position + Vector3.left * gridWorldSize.x * 0.5f + Vector3.down * gridWorldSize.y * 0.5f;

        for (int row = 0; row < numGridRows; row++)
        {
            for (int col = 0; col < numGridCols; col++)
            {
                Vector3 worldPoint = worldBottomLeft + Vector3.right * (row * nodeDiameter + nodeRadius) + Vector3.up * (col * nodeDiameter + nodeRadius);
                bool    walkable   = Physics2D.BoxCast(worldPoint, Vector2.one * nodeDiameter, 0.0f, Vector2.zero, 0.0f, unwalkableMask).collider == null;

                int   movementPenalty = 0;
                float rayHeight       = 5.0f;
                float rayRange        = 10.0f;

                // apply grid weights
                Ray          ray = new Ray(worldPoint + Vector3.forward * rayHeight, Vector3.back);
                RaycastHit2D hit = Physics2D.GetRayIntersection(ray, rayRange, walkableMask);
                if (hit)
                {
                    walkableRegionsDict.TryGetValue(hit.collider.gameObject.layer, out movementPenalty);
                }
                if (!walkable)
                {
                    movementPenalty += obstacleProximityPenalty;
                }

                grid [row, col] = new GridNode(worldPoint, walkable, row, col, movementPenalty);
            }
        }
        BlurPenaltyMap(pathingBlurSize);
    }
Exemple #10
0
    // Use this for initialization
    protected void createGrid(MeshRenderer f)
    {
        // get the mesh renderer to calculate the floor bounds
        floor       = f;
        floor_width = floor.bounds.size.x;
        floor_depth = floor.bounds.size.z;

        // init grid array
        grid = new GridNode[blockRows, blockColumns];

        // calculate the block width & depth
        block_width = floor_width / blockRows;
        block_depth = floor_depth / blockColumns;

        // get the top left point to draw from
        Vector3 TopLeftPoint = new Vector3(transform.position.x - (floor_width / 2), transform.position.y, transform.position.z + (floor_depth / 2));

        // the current position of the new block in the loop
        Vector3 currentPosition = TopLeftPoint;

        // loop through to add the blocks (nodes) to the grid
        for (int i = 0; i < blockRows; i++)
        {
            for (int j = 0; j < blockColumns; j++)
            {
                grid[i, j]         = new GridNode(currentPosition, new Vector2(block_width, block_depth)); // add a node at the current position
                currentPosition.x += block_width;                                                          // move to the right one block
            }
            // move to the next row
            currentPosition.x  = TopLeftPoint.x;
            currentPosition.z -= block_depth;
        }
    }
Exemple #11
0
    // Set the size of the grid in columns and rows.  Will lose all references to exisitng tiles so should not be called before handling them.
    public void ResizeGrid(int columnCount, int rowCount)
    {
        if (_grid != null)
        {
            Clear();
        }
        _columns = columnCount;
        _rows    = rowCount;
        _grid    = new GridNode[columnCount, rowCount];

        for (int x = 0; x < columnCount; x++)
        {
            for (int y = 0; y < rowCount; y++)
            {
                _grid[x, y] = new GridNode(new Vector2(x, y), this);

                // Hook up the neighbours to the left and below as we build the grid from the bottom-left.
                if (x > 0)
                {
                    _grid[x, y].AddNeighbour(_grid[x - 1, y]);
                    _grid[x - 1, y].AddNeighbour(_grid[x, y]);
                }

                if (y > 0)
                {
                    _grid[x, y].AddNeighbour(_grid[x, y - 1]);
                    _grid[x, y - 1].AddNeighbour(_grid[x, y]);
                }
            }
        }
    }
Exemple #12
0
    public override void CreateNodes(string mode)
    {
        gridNodes = new GridNode[rows, cols];
        int startX = (UtilGraph.GRAPH_MAX_X - ((MAX_ROWS - cols) / 2) * gridSpace);

        // Generate grid
        for (int z = 0; z < rows; z++)
        {
            int zPos = UtilGraph.GRAPH_MIN_Z + z * gridSpace;
            for (int x = 0; x < cols; x++)
            {
                int        xPos = startX - x * gridSpace;
                GameObject node = Instantiate(nodePrefab, new Vector3(xPos, 0f, zPos), Quaternion.identity);
                node.AddComponent <GridNode>();
                node.GetComponent <GridNode>().InitGridNode(algorithmName, new int[2] {
                    z, x
                });
                node.transform.parent = nodeContainerObject.transform;
                gridNodes[z, x]       = node.GetComponent <GridNode>();
            }
        }

        //GetNeighboors(gridNodes[2, 2], true);
        //CompassNeighbors(gridNodes[2, 2]);
    }
Exemple #13
0
 void Awake()
 {
     nodeGenerator = new NodeGenerator(width, height);
     gridNodes     = nodeGenerator.GetNodes();
     spriteGrid    = new SpriteGrid(width, height, this.transform, gridNodes);
     spriteGrid.CreateBackground();
 }
Exemple #14
0
    // Set all static variables to variables set in the editor
    void Initialize()
    {
        // Create a new world
        world      = new GridTile[length / tileSize, width / tileSize];
        worldNodes = new GridNode[length / tileSize + 1, width / tileSize + 1];

        // Set the seed to a random value if set seed is 0, else keep it
        if (seed == 0)
        {
            seed = Random.Range(0, int.MaxValue);
        }

        // Creating new rand instance
        rand = new Rand();

        middlePoint     = new Vector3(length / 2, 0, width / 2);
        islandSteepness = baseHeight / (radius * radius);

        // Create biome object meshes
        biomeMeshes = BuildMeshes();

        GameObject light = new GameObject();

        light.transform.SetParent(transform);
        light.AddComponent <Light>().type    = LightType.Directional;
        light.GetComponent <Light>().shadows = LightShadows.Soft;
        light.transform.rotation             = Quaternion.Euler(45, 0, 0);
        light.name = "Sun";
        light.GetComponent <Light>().shadowNormalBias = 0.94f;
        light.GetComponent <Light>().shadowBias       = 0.433f;
        light.GetComponent <Light>().shadowNearPlane  = 0.86f;
    }
 public NoiseGrid(int gridWidth, int gridHeight, int imageWidth, int imageHeight, Random rng, int randomAmplitude = int.MaxValue - 1)
 {
     gridSize             = new Vector2(gridWidth, gridHeight);
     nodes                = new GridNode[gridWidth, gridHeight];
     gridSpacing          = new Vector2(imageWidth / gridWidth, imageHeight / gridHeight);
     this.rng             = rng;
     this.randomAmplitude = randomAmplitude;
 }
Exemple #16
0
 private void CreateGrid()
 {
     if (InnerGrid == null)
     {
         Logger.Debug("[{0}] Creating grid [{1},{1}]", GetType().Name, GridBounds);
         InnerGrid = new GridNode[GridBounds, GridBounds];
     }
 }
Exemple #17
0
 private void CreateGrid()
 {
     if (InnerGrid == null)
     {
         Logger.Debug("[{0}] Creating grid [{1},{1}]", GetType().Name, GridBounds);
         InnerGrid = new GridNode[GridBounds, GridBounds];
     }
 }
Exemple #18
0
 void Start()
 {
     gridNodes       = mapManager.GetNodes();
     width           = gridNodes.GetLength(0);
     height          = gridNodes.GetLength(1);
     unitController  = new UnitController(gridNodes);
     mouseController = new MouseController(width, height);
 }
Exemple #19
0
 void Start()
 {
     gridNodes = mapManager.GetComponent <MapManager>().GetNodes();
     width     = gridNodes.GetLength(0);
     height    = gridNodes.GetLength(1);
     maskGrid  = new GameObject[width, height];
     visible   = new bool[width, height];
     CreateMask();
 }
Exemple #20
0
    public SpriteGrid(int width, int height, Transform parent, GridNode[,] gridNodes)
    {
        this.width     = width;
        this.height    = height;
        this.parent    = parent;
        this.gridNodes = gridNodes;

        spriteCreator = new SpriteCreator(width, height, parent);
    }
Exemple #21
0
    public NodeGenerator(int width, int height)
    {
        this.width  = width;
        this.height = height;

        gridNodes = new GridNode[width, height];

        GenerateNodes();
        ConnectNodes();
    }
        private void createGrid()
        {
            grid = new GridNode[gridWidth, gridHeight];
            filledArray = new bool[gridWidth, gridHeight];
            GridNode tile;
            for (int r = 0; r < gridWidth; r++)
            {
                for (int c = 0; c < gridHeight; c++)
                {
                    tile = Instantiate(Tile);
                    Vector2 gridPos = new Vector2(r, c);
                    tile.transform.position = calcWorldCoord(gridPos);
                    grid[r, c] = tile;
                    filledArray[r, c] = false;
                }
            }

            //NOTES on how the grid system works.
            //It's a HACK. Just how it is. Nevertheless:
            //UP: 			y--
            //DOWN:			y++
            //RIGHT:		x--
            //LEFT:			x++
            //Input FORMAT:	[y,x]
            for (int x = 0; x < gridHeight; x++)
            {
                for (int y = 0; y < gridWidth; y++)
                {
                    if (y > 0)
                        grid[y, x].Up = grid[y - 1, x];
                    if (y < gridWidth - 1)
                        grid[y, x].Down = grid[y + 1, x];
                    if (x > 0)
                        grid[y, x].Right = grid[y, x - 1];
                    if (x < gridHeight - 1)
                        grid[y, x].Left = grid[y, x + 1];
                    grid[y, x].Position = new Vector2(y, x);
                }
            }

            for (int x = 0; x < gridHeight / 2; x++)
            {
                for (int y = 0; y < gridWidth; y++)
                {
                    grid[y, x].Type = Util.Enums.FieldType.Blue;
                }
            }
            for (int x = gridHeight / 2; x < gridHeight; x++)
            {
                for (int y = 0; y < gridWidth; y++)
                {
                    grid[y, x].Type = Util.Enums.FieldType.Red;
                }
            }
        }
Exemple #23
0
    private GridNode findNearestWater(float[,] altitudeMap, Coord current, GridNode[,] grid)
    {
        GridNode tempNode = new GridNode(altitudeMap[current.getY(), current.getX()], current, current);

        if (tempNode.getAltitude() < 0)
        {
            return(tempNode);
        }
        bool isFirstIter = true;
        int  i = 0, j = 0;

        if (current.getX() > 0)
        {
            j = current.getX() - 1;
        }
        if (current.getY() > 0)
        {
            i = current.getY() - 1;
        }
        int lastWaterY = 0;
        int lastWaterX = 0;

        if (i < current.getY() && j < current.getX())
        {
            lastWaterY = grid[i, j].getNearestWater().getY();
            lastWaterX = grid[i, j].getNearestWater().getX();
        }
        for (i = lastWaterY; i < altitudeMap.GetLength(0); i++)
        {
            for (j = lastWaterX; j < altitudeMap.GetLength(0); j++)
            {
                k++;
                if (altitudeMap[i, j] < 0)
                {
                    int x = current.getX() - j;
                    int y = current.getY() - i;
                    if (isFirstIter)
                    {
                        tempNode.setNearestWater(new Coord(j, i));
                        isFirstIter = false;
                    }
                    else if (Mathf.Abs(y) > tempNode.getDistanceFromWater())
                    {
                        return(tempNode);
                    }
                    if (Mathf.Sqrt(x * x + y * y) < tempNode.getDistanceFromWater())
                    {
                        tempNode.setNearestWater(new Coord(j, i));
                    }
                }
            }
        }
        return(tempNode);
    }
Exemple #24
0
 public void InitGrid(GridNode[,] _grid, float _gridSizeX, float _gridSizeY, Vector3 _worldGridBootomLeft)
 {
     grids               = _grid;
     rMax                = grids.GetLength(0);
     cMax                = grids.GetLength(1);
     gridSizeX           = _gridSizeX;
     gridSizeY           = _gridSizeY;
     gridHalfY           = gridSizeY / 2;
     gridHalfX           = gridSizeX * .5f;
     worldGridBootomLeft = _worldGridBootomLeft;
 }
Exemple #25
0
 void CreateGrid()
 {
     _grid = new GridNode[rows, columns];
     for (int r = 0; r < rows; r++)
     {
         for (int c = 0; c < columns; c++)
         {
             GridBlock block = manager.GetBlock(new GridPosition(r, c));
             _grid[r, c] = new GridNode(block);
         }
     }
 }
Exemple #26
0
    public PathFinder(GridNode[,] gridNodes)
    {
        this.gridNodes = gridNodes;
        this.width     = gridNodes.GetLength(0);
        this.height    = gridNodes.GetLength(1);

        pathCost  = new int[width, height];
        sourceDir = new int[width, height];


        ResetPath();
    }
    private void CreateGrid(int sizeX, int sizeZ, float percentageOfObstacles)
    {
        grid = new GridNode[sizeX, sizeZ];

        for (int i = 0; i < sizeX; ++i)
        {
            for (int j = 0; j < sizeZ; ++j)
            {
                //Create grid model
                GameObject tile = Instantiate(tilePrefab, new Vector3(i, 0, j), Quaternion.identity, tilesParent).gameObject;
                tile.GetComponent <GridElement>().Init(percentageOfObstacles);

                //Create logic grid
                Vector3  tmp  = new Vector3(i * xScaleFactor, 0, j * zScaleFactor);
                GridNode node = new GridNode(i, 0, j, tmp, null);


                //Check if is walkable
                Collider[] collisionNode = Physics.OverlapBox(tmp, DebugCubeSize / 2, Quaternion.identity);

                if (collisionNode.Length > 0)
                {
                    bool isWalkable = false;

                    foreach (Collider col in collisionNode)
                    {
                        GridElement elem = col.GetComponent <GridElement>();

                        if (elem != null)
                        {
                            if (elem.IsWalkable && node.Element == null)
                            {
                                isWalkable = true;
                            }

                            else
                            {
                                isWalkable   = false;
                                node.Element = elem;
                            }
                        }
                    }

                    node.IsWalkable   = isWalkable;
                    node.TileRenderer = tile.GetComponent <Renderer>();
                }

                grid[i, j] = node;
                nodeVizualizer.Add(node);
            }
        }
    }
Exemple #28
0
 private void BuildGraph()
 {
     Graph = new GridNode[bounds.size.x, bounds.size.y];
     for (int i = 0; i < Graph.GetLength(0); i++)
     {
         for (int j = 0; j < Graph.GetLength(1); j++)
         {
             var worldPos   = new Vector2(bounds.xMin + i, bounds.yMin + j);
             var isWalkable = Physics2D.OverlapCircleAll(worldPos + (Vector2.one * .5f), Mathf.Sqrt(2) / 2, obstacleMask).Length == 0;
             Graph[i, j] = new GridNode(new Vector2Int(i, j), isWalkable);
         }
     }
 }
Exemple #29
0
        public Board(GridNode[,] grids, int size)
        {
            gridsize = size;
            nodes    = new BoardNode[gridsize, gridsize];

            for (int row = 0; row < gridsize; ++row)
            {
                for (int col = 0; col < gridsize; ++col)
                {
                    nodes[row, col] = new BoardNode(row, col, grids[row, col].GetPos());
                }
            }
        }
        public override void PlaceBombs(ref GridNode[,] matrix)
        {
            int placedBombs = 0;

            while (placedBombs < maxBombsCount)
            {
                var randomLower = Random.Range(0, matrix.GetUpperBound(0));
                var randomUpper = Random.Range(0, matrix.GetUpperBound(0));
                var node        = matrix[randomLower, randomUpper];
                node.containsBomb = true;
                placedBombs++;
            }
        }
Exemple #31
0
        public GridNode[,] Bake(GridNode[,] map)
        {
            _generatedMap = map;
            for (var x = 0; x < _generatedMap.GetLength(0); x++)
            {
                for (var y = 0; y < _generatedMap.GetLength(1); y++)
                {
                    BakeNode(_generatedMap[x, y]);

                    _generatedMap[x, y] = _currentChecking;
                }
            }
            return(_generatedMap);
        }
Exemple #32
0
 public GridLevel(ContentManager content) : base()
 {
     //Initialize the grid with the size of the level
     grid = new GridNode[LEVEL_SIZE, LEVEL_SIZE];
     //Fill the grid with GridItems
     for (int x = 0; x < LEVEL_SIZE; ++x)
     {
         for (int y = 0; y < LEVEL_SIZE; ++y)
         {
             grid[x, y]        = new GridNode(content, new Vector2(NODE_SIZE * x, NODE_SIZE * y));
             grid[x, y].Parent = this; //Note that the grid array is not part of the standard children list
                                       //and must therefore be handled manually
         }
     }
 }
        ///<summary> A public constructor for a GridGraph</summary>
        ///<param name="m"> Number of rows in a grid </param>
        ///<param name="n"> Number of columns in a grid </param>
        public GridGraph(int m, int n)
        {
            // make a new node matrix
            grid = new GridNode[m, n];
            this.m = m;
            this.n = n;

            // make all the nodes and connect them to their adjacent nodes
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                {
                    grid[i, j] = new GridNode(i, j);
                    grid[i, j].Edges = this.adjacentToNode(i, j);
                }
        }
Exemple #34
0
    public static GridNode FindGridNode(Vector3 position)
    {
        GridNode[,] gridNodes = TerrainController.thisTerrainController.worldNodes;
        float tileSize = TerrainController.thisTerrainController.tileSize;

        int x = Mathf.RoundToInt(position.x / tileSize);
        int z = Mathf.RoundToInt(position.z / tileSize);

        if (gridNodes.GetLength(0) <= x || gridNodes.GetLength(1) <= z)
        {
            return(null);
        }

        return(gridNodes[x, z]);
    }
Exemple #35
0
        public Grid(int gridWidth, int gridHeight, int nodeSize)
        {
            int nodeArrayWidth = gridWidth / nodeSize;
            int nodeArrayHeight = gridHeight / nodeSize;

            if (gridWidth / (float)nodeSize != gridWidth / nodeSize)
                nodeArrayWidth++;
            if (gridHeight / (float)nodeSize != gridHeight / nodeSize)
                nodeArrayHeight++;

            nodes = new GridNode[nodeArrayWidth, nodeArrayHeight];
            NodeSize = nodeSize;

            createNodes(nodeArrayWidth, nodeArrayHeight);
            calculateNodeNeighbors(nodeArrayWidth, nodeArrayHeight);
        }
Exemple #36
0
 public LongPathGrid(Vector3 terrainCentre, Vector2 terrainSize, int nodeRadius, LayerMask unwalkableLayer)
 {
     this.gridWorldSize = terrainSize;
     this.gridWorldCentre = terrainCentre;
     gridSizeX = Mathf.RoundToInt(gridWorldSize.x/(nodeRadius*2));
     gridSizeY = Mathf.RoundToInt(gridWorldSize.y/(nodeRadius*2));
     grid = new GridNode[gridSizeX,gridSizeY];
     gridWorldOrigin = gridWorldCentre - Vector3.right * gridWorldSize.x/2 - Vector3.forward * gridWorldSize.y/2;
     for (int x = 0; x < gridSizeX; ++x) {
         for (int y = 0; y < gridSizeY; ++y) {
             Vector3 worldPoint = gridWorldOrigin + Vector3.right * (x * (nodeRadius * 2) + nodeRadius)
                     + Vector3.forward * (y * (nodeRadius * 2) + nodeRadius);
             // bool walkable = !(Physics.CheckSphere(worldPoint, nodeRadius, unwalkableLayer));
             bool walkable = EmptyBox(worldPoint, nodeRadius, unwalkableLayer);
             grid[x,y] = new GridNode(walkable, worldPoint,x,y);
         }
     }
 }
Exemple #37
0
        public void Create(int dimension)
        {
            _dimension = dimension;
            _node_width = gridNodePrefab.GetComponent<Renderer>().bounds.size.x;
            _node_height = gridNodePrefab.GetComponent<Renderer>().bounds.size.y;
            Vector2 node_position = new Vector2( _node_width * 0.5f, _node_height * -0.5f );
            _nodes = new GridNode[_dimension, _dimension];
            for( int row = 0; row < _dimension; ++row ) {
                for( int col = 0; col < _dimension; ++col ) {
                    GridNode node = CreateNode( row, col );
                    node.transform.localPosition = node_position;
                    _nodes[ row, col ] = node;

                    node_position.x += _node_width;
                }
                node_position.x = _node_width * 0.5f;
                node_position.y -= _node_height;
            }
        }
Exemple #38
0
    //Create grid
    public GridNode[,] generate() {
        //Instantiate 2D Node Array
        grid = new GridNode[gridSize.x, gridSize.y];

        //Calculate 3D location of bottom left grid node
        bottomLeft = worldPosition - (Vector3.right * worldSize.x / 2) - (Vector3.up * worldSize.y / 2);
        
        //Iterate through entire grid
        for(int x = 0; x < gridSize.x; x++) {
            for(int y = 0; y < gridSize.y; y++) {
                //Calculate Node parameters
                Vector3 pos = bottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.up * (y * nodeDiameter + nodeRadius); //Position of Node in 3d Space
                bool walkable = !(Physics2D.OverlapCircle(pos, nodeRadius, unwalkableMask)); //Check if node is traversable

                //Create and store node with specified parameters 
                grid[x, y] = new GridNode(pos, walkable, new Point(x, y));
            }
        }

        //Return Grid
        return grid;
    }
Exemple #39
0
        private void InitializeGrid()
        {
            gridSize = config.GetSetting<int>( "Resolution" );
            nodeMass = config.GetSetting<float>( "NodeMass" );
            springConstant = config.GetSetting<float>( "SpringConstant" );
            springDamping = config.GetSetting<float>( "SpringDamping" );
            springXEquilibrium = renderer.FullscreenSize.Width / gridSize;
            springYEquilibrium = renderer.FullscreenSize.Height / gridSize;

            grid = new GridNode[ gridSize, gridSize ];

            for ( int x = 0; x < gridSize; ++x )
            {
                for ( int y = 0; y < gridSize; ++y )
                {
                    grid[ x, y ] = new GridNode();
                    grid[ x, y ].Mass = nodeMass;
                }
            }

            int dx = ( int )springXEquilibrium;
            int dy = -( int )springYEquilibrium;

            int startX = -renderer.FullscreenSize.Width / 2 + dx / 2;
            int startY = renderer.FullscreenSize.Height / 2 + dy / 2;

            int px = startX;
            int py = startY;

            for ( int x = 0; x < gridSize; ++x )
            {
                for ( int y = 0; y < gridSize; ++y )
                {
                    grid[ x, y ].Pos = new Vector2( ( float )px, ( float )py );

                    py += dy;
                }

                py = startY;
                px += dx;
            }
        }
Exemple #40
0
        private void BuildGridFromSnapshot()
        {
            if ( pendingNodeSpacing != 0 && pendingWorldSpace != Rectangle.Empty && pendingObstacles != null)
            {
                nodeSpacing = pendingNodeSpacing;

                //initialize array size
                nodes = new GridNode[pendingWorldSpace.Width / nodeSpacing, pendingWorldSpace.Height / nodeSpacing];

                currentObstacles = pendingObstacles;

                ////loop and weigh
                for (int x = 0; x < nodes.GetLength(0); ++x)
                {
                    for (int y = 0; y < nodes.GetLength(1); ++y)
                    {
                        GridNode currentNode = nodes[x, y] = new GridNode();
                        currentNode.LocationInGrid = new Point(x, y);
                    }
                }

                pendingObstacles = null;
                pendingWorldSpace = Rectangle.Empty;
                pendingNodeSpacing = 0;
            }
        }
 void Start()
 {
     grid = FindObjectOfType<GridManager>().Grid;
 }
Exemple #42
0
 public void LoadNodes(GridNode[,] storedNodes)
 {
     nodes = storedNodes;
 }
Exemple #43
0
    void Update()
    {
        //Debug.Log("Health" + player.GetComponent<PlayerController>().curr_Health);
        player = GameObject.FindGameObjectWithTag("Player");
        Vector3 spotVector = player.transform.position - transform.position + new Vector3(0f, -1f, 0f);
        if (Physics.Raycast(transform.position, spotVector, out hit, MAX_MOVE - 3)) // set white
        {
            if (hit.collider.tag == "Player")
            {
                gameObject.GetComponentInChildren<Renderer>().material = spottedMat;
                if (alert && !player.GetComponent<PlayerController>().imHidden)
                {
                    alarmSound.Play();
                    alert = false;
                }
            }
        }
        else // set black
        {
           gameObject.GetComponentInChildren<Renderer>().material = hiddenMat;
        }

        if (GameMaster.CurrentState == GameMaster.GameState.GAME_LOSS)
        {
            gameLoss = true;
            Debug.Log("Game has been lost");
        }

        //Sets a timer for the laser
        if (laser.enabled)
        {
            laserDecayTime -= Time.deltaTime;
            laser.material = laserMat;
            linePos[0] = transform.position;
            linePos[1] = player.transform.position;
            laser.useLightProbes = true;
            laser.SetPositions(linePos);

            if (laserDecayTime < 0)
            {
                laser.enabled = false;
            }
        }
        else
        {
            laserDecayTime = laserRenderTime;
        }

        if (GameMaster.CurrentState == GameMaster.GameState.ENEMY_TURN)
        {
            //Reset Game Board.
            if (init)
            {
                turnInProgress = true;
                playerFound = false;
                shot = true;
                scan = true;
                playerNode = new GridNode();
                playerPos = player.transform.position;
                curPos = transform.position;

                if (!finishedList.Contains(id))
                {
                    EnemySearchPlane = new GridNode[(int)MAX_SPOT, (int)MAX_SPOT];
                    finishedList.Add(id);
                    turnQueue.Enqueue(id);
                    Debug.Log(id + " Checking in, finishedList Count: " + finishedList.Count);
                }

                if (MAX_ENEMIES == finishedList.Count)
                    init = false;
            }
            else
            {
                if (turnQueue.Peek().Equals(id))
                {
                    if(scan)
                    {
                        StartCoroutine("initESP");
                        scan = false;
                    }

                    //Player is hidden
                    if (player.GetComponent<PlayerController>().imHidden)
                    {
                        turnQueue.Clear();
                        finishedList.Clear();
                        GameMaster.CurrentState = GameMaster.GameState.ENVIRONMENT_TURN;
                    }

                    //Player ended enemy turn with emp.
                    else if (emp)
                    {
                        emp = false;
                        Destroy(empInst);
                        init = true;

                        turnQueue.Clear();
                        finishedList.Clear();
                        Debug.Log("PLAYER_TURN -from enemyLOS EMPed");
                        GameMaster.CurrentState = GameMaster.GameState.ENVIRONMENT_TURN;
                    }

                    else if (finishedList.Count > 0 && finishedList.Contains(id))
                    {
                        //Movement
                        if (playerFound)
                        {
                            moveList = new ArrayList();
                            PathFinding(MAX_MOVE, MAX_MOVE);
                            if (moveList.Count > 0)
                            {
                                dest = (GridNode)moveList[moveList.Count - 1];
                                moveEnemy();
                            }
                            else
                            {
                                dest.coords = transform.position;
                            }

                            if (moveList.Count == 0)
                            {
                                //Checks if player is obstructed by obstacle. 
                                Vector3 heading = player.transform.position - transform.position + new Vector3(0f, -1f, 0f);
                                if (Physics.Raycast(transform.position, heading, out hit, MAX_SPOT))
                                {
                                    //Combat
                                    if (shot)
                                    {

                                        ShootAtPlayer(dest.coords);
                                        linePos[0] = transform.position;
                                        linePos[1] = player.transform.position;
                                        laser.SetPositions(linePos);
                                        laser.enabled = true;
                                        shot = false;
                                    }
                                    if(player.GetComponent<PlayerController>().curr_Health <= 0)
                                    {
                                        gameLoss = true;
                                        Debug.Log("Game Loss = " + gameLoss);
                                    }
                                }
                            }
                        }
                    }

                    //Change the Game State to PLAYER_TURN.
                    if (finishedList.Count > 0 && finishedList.Contains(id))
                    {
                        finishedList.Remove(id);
                        turnQueue.Dequeue();
                        if (gameLoss)
                        {
                            finishedList.Clear();
                            turnQueue.Clear();
                        }
                        Debug.Log(id + " Checking out, finishedList Count: " + finishedList.Count);
                    }

                    if (finishedList.Count <= 0)
                    {
                        Debug.Log("PLAYER_TURN -from enemyLOS");
                        init = true;
                        alert = true;
                        if (disoriented)
                        {
                            disoriented = false;
                            Destroy(disorientedInst);
                        }

                        emp = false;
                        if(!gameLoss)
                            GameMaster.CurrentState = GameMaster.GameState.ENVIRONMENT_TURN;
                        else
                        {
                            Debug.Log("Game Loss in finish list check");
                            GameMaster.CurrentState = GameMaster.GameState.GAME_LOSS;
                        }
                    }

                    //Recalculating enemy instance Array posistion. 
                    //UpdateIndex();
                }
            }
        }
    }
Exemple #44
0
 //Creates grid with the size of Vector2 gridWorldSize
 private void createGrid()
 {
     gridLength = getArrayPosition(gridWorldSize.x);
     gridHeight = getArrayPosition(gridWorldSize.y);
     grid = new GridNode[gridLength,gridHeight];
     for(int i=0; i<gridLength; i++){
         for(int n=0; n<gridHeight; n++){
             Vector3 nodePosition = new Vector3(i*nodeDiameter+nodeDiameter/2, 0 ,n*nodeDiameter+nodeDiameter/2);
             bool isBlocked = false;
             if(n != 0 || n != gridHeight -1 || i != 0 || i != gridLength -1){
                 isBlocked = Physics.CheckSphere(nodePosition,nodeDiameter, SnorlaxMask);
             }
             grid[i,n] = new GridNode(isBlocked,nodePosition,i,n);
         }
     }
 }
Exemple #45
0
    /*	public function drawPath(path:Array, color:uint = 0xFF0000, transparent:Boolean = false):Sprite
    {
        var gw2:int = AStar.grid_width/2;
        var gh2:int = AStar.grid_height/2;
        if(path == null)
        {
            //trace("no path");
            return new Sprite();
        }
        var _dummySprite:Sprite = new Sprite();
        _dummySprite.graphics.clear();

        _dummySprite.graphics.beginFill(0x000000);
        _dummySprite.graphics.lineStyle(3, color);

        for(var i:int = path.length-1; i >0; i--)
        {
            var start:GridNode = path[i];
            var end:GridNode = path[i-1];

            if(transparent)
            {
                _dummySprite.graphics.lineStyle(3, color, 0.25);
            }

            _dummySprite.graphics.moveTo(start.worldx+gw2, start.worldy+gh2);
            _dummySprite.graphics.lineTo(end.worldx+gw2, end.worldy+gh2);
        }
        _dummySprite.graphics.endFill();

        _dummySprite.name = "path";
        return _dummySprite;
        //this.getChildByName(
    }*/
    public void createGrid(int width, int height)
    {
        grid = new GridNode[width,height];

        int xx = 0;
        int yy = 0;

        for(xx = 0; xx < width; xx++)
        {
            for(yy = 0; yy < height; yy++)
            {
                GridNode tempnode = new GridNode();
                tempnode.worldx = xx*grid_width; // real world coordinates
                tempnode.worldy = yy*grid_height; // real world coordinates
                tempnode.x = xx; // real world coordinates
                tempnode.y = yy; // real world coordinates

                tempnode.squareType = GridNode.WALKABLE;

                tempnode.parent = null;
                grid[xx,yy] = tempnode;
            }//for
        }//for
    }
Exemple #46
0
 public PathingGrid()
 {
     nodes = new GridNode[1, 1];
 }