Game Development Reference
In-Depth Information
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
if (visible)
spriteBatch.DrawString(spriteFont, text, this .GlobalPosition, color);
}
Again, we are using the global position here, so that text-based game objects can
also be a part of the hierarchy. It can be useful to use a different origin for displaying
text, just as we did with some of the sprites in the Painter game. We, therefore, add
a member variable origin of type Vector2 to the TextGameObject class, as well as a
property to access and modify it. We then call the extended version of the Draw
method from the SpriteBatch class to take the origin into account.
Now, we define a ScoreGameObject class that inherits from the TextGameObject
class. We add one member variable to this class which holds the current score:
protected int score;
Furthermore, we add a property Score that allows to retrieve or modify the current
score. We override the Update method to update the text that should be displayed on
the screen. For easier text drawing, we want to set the origin of the text to the bottom
right. This results in the text being right-aligned, and the position is independent of
the font size. Setting the origin is done using the Origin property we added to the
TextGameObject class, and we can determine what the origin should be by calculating
the size of the text. The SpriteBatch class has a very useful method for that called
MeasureText . So, we add another property called Tex t S i z e to the TextGameObject class
that calculates the text size for us:
public Vector2 TextSize
{
get { return spriteFont.MeasureString(text); }
}
Now we can use that property in the Update method of the score game object to set
the right origin. For the complete ScoreGameObject class, see Listing 16.2 .Wenow
only have to create an instance of this class and add it to the game world. Inside the
JewelJamGameWorld class, we place the instructions needed for creating the object.
We also add a frame upon which we can draw the current score. These instructions
do all the work:
SpriteGameObject scoreframe = new SpriteGameObject("spr_scoreframe", 1);
scoreframe.Position = new Vector2(20, 20);
this .Add(scoreframe);
ScoreGameObject score = new ScoreGameObject(2, "score");
score.Position = new Vector2(270, 80);
this .Add(score);
Search WWH ::




Custom Search