Game Development Reference
In-Depth Information
The next step is to determine if the sprite should be mirrored or not. We can indicate
if a sprite should be mirrored by setting a sprite effect , as follows:
SpriteEffects spriteEffects = SpriteEffects.None;
if (mirror)
spriteEffects = SpriteEffects.FlipHorizontally;
Finally, we draw the sprite part on the screen, as follows:
spriteBatch.Draw(sprite, position, spritePart, Color.White,
0.0f, origin, 1.0f, spriteEffects, 0.0f);
The SpriteGameObject class now becomes rather straightforward. Its main task is to
make sure the sprite is properly drawn on the screen. This is done in the Draw method
as follows:
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
if (!visible || sprite == null )
return ;
sprite.Draw(spriteBatch, this .GlobalPosition, origin);
}
For the complete SpriteGameObject class, see the PenguinPairs1 example belonging to
this chapter.
19.5 Finalizing the Example
In the PenguinPairs1 example, we draw a background and a penguin on the screen. In
order to test our new SpriteGameObject class, we will modify the currently selected
sheet index by pressing the left and right arrow buttons. This is done easily in the
PenguinPairs class:
SpriteGameObject penguin = gameWorld.Find("penguin") as SpriteGameObject;
if (inputHelper.KeyPressed(Keys.Left))
penguin.Sprite.SheetIndex
;
else if (inputHelper.KeyPressed(Keys.Right))
penguin.Sprite.SheetIndex++;
−−
By the way, because we handle all the sprite sheet aspects inside the SpriteSheet
class, it is now completely straightforward to draw the penguin exactly in the middle
of the screen, as follows:
penguin.Width,
penguin.Position = new Vector2(screen.X
penguin.Height) / 2;
screen.Y
This will work for any sprite sheet of any dimension!
Search WWH ::




Custom Search