Game Development Reference
In-Depth Information
In addition, we change the position of the object that was changed from being the
leftmost object to the rightmost object. The result of this positional change is a nice
motion effect, as we will see later on. The method ShiftRowRight is quite similar to
this method, have a look for yourself.
We also want to add a method that gives us the anchor position in the grid for
any game object. This method is going to be useful later on. As a parameter, this
method expects a game object, and it returns a Vector2 object containing the anchor
position. Here is the complete method:
public Vector2 GetAnchorPosition(GameObject s)
{
for ( int x = 0; x < Columns; x++)
for ( int y=0;y<Rows;y++)
if (grid[x, y] == s)
return new Vector2(x
cellWidth, y cellHeight);
return Vector2.Zero;
}
This method uses (again) a nested for -instruction to look for the game object that
was passed as a parameter. Once this object has been found, we calculate its anchor
position based on the x and y indices in the grid, together with the cell size. If the
object was not found, we return the zero vector ( Vector2.Zero ). Since this method is
useful for almost all grids, we added this method to the GameObjectGrid class.
Because the GameObjectGrid class inherits from GameObject , we need to define
what the different game loop methods do. In this case, it is quite straightforward.
The nice thing in C# is that we can actually use foreach on arrays as well, even if
they are multidimensional. So, for instance the Update method becomes
public override void Update(GameTime gameTime)
{
foreach (GameObject obj in grid)
obj.Update(gameTime);
}
Both the HandleInput method and the Draw method do something very similar. Note
that when drawing the objects in a grid, we do not take the drawing layer of each
game object into account, to keep things simple. Can you extend the Draw method
of this class so that it does take care of it? Hint: copy the game objects from the grid
to a list, and add them in the same fashion as we did in the GameObjectList class.
14.4.5 Moving Smoothly on the Grid
For our objects to move smoothly on the grid, we are going to use the velocity and
the position member variables that are a part of the GameObject class. We are going
Search WWH ::




Custom Search