Game Development Reference
In-Depth Information
Our GameObjectGrid class inherits again from GameObject , which makes it easy
to incorporate the grid into any hierarchy of game objects. Obviously, there is a
member variable for storing a grid of game objects:
GameObject[,] grid;
As you can see, we refer to the actual game objects in the grid, as opposed to using
integers like in the previous version. The advantage is that we can now store any
kind of game object as a part of the grid. Because we need to be able to calculate
anchor positions, we also need to know the size of a single element in the grid.
Therefore we also add two member variables to store the size of a single cell in the
grid:
protected int cellWidth, cellHeight;
In order to modify the cell size, we add two properties to the GameObjectGrid class:
CellWidth and CellHeight . The constructor of the class needs three parameters: the
number of rows and columns in the grid, and the drawing layer. Inside the construc-
tor, we initialize the two-dimensional array according to the size and we store the
value null in each of the grid locations so that it is clear that the entire grid is empty
on creation. The complete GameObjectGrid constructor is given as follows:
public GameObjectGrid( int rows, int columns, int layer = 0) : base (layer)
{
grid = new GameObject[columns, rows];
for ( int x = 0; x < columns; x++)
for ( int y=0;y<rows;y++)
grid[x, y] = null ;
}
Now we need to write a method for adding a game object. For now, we are going to
keep things extremely basic. Let us just assume that the Add method simply looks
for the first empty position in the grid and inserts the game object there. This means
that we do not have any control over where objects are placed, but for the example
game, this behavior is sufficient. So, inside the Add method, we place a nested for -
instruction to walk through the elements in the array. Once we find an empty spot,
we insert the game object there and we return from the method. Next to adding
the object, we also set a few parameters inside the game object. For example, we
have to set the parent of the game object to the grid object, just like we did in
the GameObjectList class. We also set the position of the game object to its anchor
position in the grid. Then, the complete Add method becomes
public void Add(GameObject obj)
{
for ( int x = 0; x < Columns; x++)
for ( int y=0;y<Rows;y++)
Search WWH ::




Custom Search