Game Development Reference
In-Depth Information
variables, or that extracts some meaningful information from them for the caller of
the method. Methods can manipulate multiple member variables. For example, the
Reset method changes the color of the cannon, as well as the angle of the barrel.
Next to the Reset method, we also add a method called Draw that will draw the
cannon on the screen at its position, in the desired color. Because the SpriteBatch
object is defined inside the Painter class, we need to pass it as a parameter. And since
the Draw method in the Painter class also gets a GameTime parameter, we pass this
parameter along to the Draw method in the Cannon class. The outline of the Draw
method is then given as follows:
public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
// draw the cannon sprites
}
Inside the Draw method, we need to draw the cannon barrel at an angle, and the
color indicator disc. We simply copy the two draw instructions that do this from the
previous version of the game, so then the complete Draw method is as follows:
public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
spriteBatch.Draw(cannonBarrel, position, null , Color.White, angle, barrelOrigin,
1f, SpriteEffects.None, 0);
spriteBatch.Draw(currentColor, position, null , Color.White, 0f, colorOrigin,
1f, SpriteEffects.None, 0);
}
Now we can call this Draw method in the Painter class. The Draw method is not static,
which means we have to call it on an object. The logical candidate for this is of
course the cannon object that we created in the LoadContent method. So, the following
instructions in the Painter.Draw method will draw everything on the screen:
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin();
spriteBatch.Draw(background, Vector2.Zero, Color.White);
cannon.Draw(gameTime, spriteBatch);
spriteBatch.End();
We let the cannon draw itself, so to speak. As you can see, the Draw method inside
the Cannon class specifies what we are going to do with the member variables. In this
case, we are going to draw them on the screen. Methods work on objects, and this is
a very clear example of that. Also, what we are slowly working toward is a software
design where each game object deals with its own stuff. For instance, the Cannon
class has to deal with loading the sprites that are part of it, as well as drawing and
resetting itself. In a later stage, we will add more capabilities to the Cannon class,
such as handling input.
Search WWH ::




Custom Search