Datasheet
One final thing you are going to add for this first project is the capability to scroll the background with
the cursor keys or a gamepad, and then you render the scrollable tiles to the whole background. To cap-
ture the gamepad and keyboard input, you modify the
Update method a little:
float scrollPosition = 0;
protected override void Update(GameTime gameTime)
{
// Get current gamepad and keyboard states
GamePadState gamePad = GamePad.GetState(PlayerIndex.One);
KeyboardState keyboard = Keyboard.GetState();
// Back or Escape exits our game on Xbox 360 and Windows
if (gamePad.Buttons.Back == ButtonState.Pressed ||
keyboard.IsKeyDown(Keys.Escape))
this.Exit();
// Move 400 pixels each second
float moveFactorPerSecond = 400 *
(float)gameTime.ElapsedRealTime.TotalMilliseconds / 1000.0f;
// Move up and down if we press the cursor or gamepad keys.
if (gamePad.DPad.Up == ButtonState.Pressed ||
keyboard.IsKeyDown(Keys.Up))
scrollPosition += moveFactorPerSecond;
if (gamePad.DPad.Down == ButtonState.Pressed ||
keyboard.IsKeyDown(Keys.Down))
scrollPosition -= moveFactorPerSecond;
base.Update(gameTime);
} // Update(gameTime)
The first few lines are the same as before. Then you calculate how many pixels you would move this
frame. If a frame would take 1 second,
moveFactorPerSecond would be 400; for 60 frames it would be
400/60. Because you use floats here instead of just integers, you can have a couple of thousand frames
and the movement is still 400 pixels per second if you press up or down.
The variable
scrollPosition is changed if the user presses up or down. In your draw method, you
can now render each tile and add the
scrollPosition to the y position to move the background up
and down:
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Green);
sprites.Begin();
int resolutionWidth = graphics.GraphicsDevice.Viewport.Width;
int resolutionHeight = graphics.GraphicsDevice.Viewport.Height;
for (int x = 0; x <= resolutionWidth / backgroundTexture.Width;
x++)
for (int y = -1; y <= resolutionHeight / backgroundTexture.Height;
y++)
{
Vector2 position = new Vector2(
x * backgroundTexture.Width,
y * backgroundTexture.Height +
((int)scrollPosition) % backgroundTexture.Height);
sprites.Draw(backgroundTexture, position, Color.White);
20
Part I: XNA Framework Basics
61286c01.qxd:WroxPro 1/21/08 3:44 PM Page 20