Game Development Reference
In-Depth Information
protected override void Update(GameTime gameTime)
{
int yposition = 480
gameTime.TotalGameTime.Milliseconds / 2;
balloonPosition = new Vector2(300, yposition);
}
In this example, we first store an expression containing the millisecond fraction of
the current time in a variable called yposition . We then assign a value to the variable
balloonPosition (which is of type Vector2 ) and in it we store the y -position that we just
calculated. As an x -value, we choose 300 (which is about halfway horizontally on
the screen). Because the x -position will always be 300 and the y -position is varying,
the result will be a balloon flying from the bottom of the screen to the top of the
screen. We need to slightly change the Draw method in order to actually draw the
balloon at the right position. The call to the Draw method in the SpriteBatch class will
then become:
spriteBatch.Draw(balloon, balloonPosition, Color.White);
Try to play around with the numbers used to calculate the new balloon position. Can
you make the balloon move from left to right? Or diagonally across the screen?
4.3.5 Adding a Background Sprite
Building games with only a plain white background is somewhat boring, so we can
also make it a bit more visually appealing by displaying a background sprite. This
means we have to load another sprite in the LoadContent method and extend the Draw
method in order to draw it. The final version of this program is called FlyingSprites
and you can find the complete source code in the sample solution belonging to
this chapter. If you run the program FlyingSprites from the samples, you see that
now two sprites are drawn: a background, and on top of that, a balloon. In order to
achieve this, we have introduced another variable of type Texture2D to contain the
background sprite. Like the balloon variable, this variable is declared at the class
level:
Texture2D balloon, background;
As you can see, just like with integers, we can declare multiple variables of the same
type in a single instruction. Also, there are now two calls to the Draw method of the
SpriteBatch class, instead of one:
spriteBatch.Draw(background, Vector2.Zero, Color.White);
spriteBatch.Draw(balloon, balloonPosition, Color.White);
Search WWH ::




Custom Search