Josh-CO Dev

Solving the worlds problems one line of code at a time.

XNA – Code example. Scrolling Background on Keyboard Movement

Leave a comment

One of the things that I am trying to work up to is writing a scrolling platform game. I decided to write a demo that would scroll the background on keypress and found that it was fairly easy to do. Here is an example of the update code that I used and I am also putting the solution in a zip. It could stand to be more object oriented, but it can be tidied up later. Next step will be to make the sprite move and the background only scroll when the sprite is near the edge of the screen. This is an extension and some customization on top of the tutorial found here: Scrolling 2d Background

// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

KeyboardState keyState = Keyboard.GetState();
string leftOrRight = null;
Vector2 aDirection = Vector2.Zero;

if (keyState.IsKeyDown(Keys.Left))
leftOrRight = “left”;
else if(keyState.IsKeyDown(Keys.Right))
leftOrRight = “right”;

// TODO: Add your update logic here
switch(leftOrRight) //if moving right the bg needs to move left
case “right”:
if (bg1.position.X < -bg1.size.Width)
bg1.position.X = bg3.position.X + bg3.size.Width;

if (bg2.position.X < -bg2.size.Width)
bg2.position.X = bg1.position.X + bg1.size.Width;

if (bg3.position.X bg1.size.Width)
bg1.position.X = bg3.position.X – bg3.size.Width;

if (bg2.position.X > bg2.size.Width)
bg2.position.X = bg1.position.X – bg1.size.Width;

if (bg3.position.X > bg3.size.Width)
bg3.position.X = bg2.position.X – bg2.size.Width;

aDirection = new Vector2(1, 0);

Vector2 aSpeed = new Vector2(130, 0);

bg1.position += aDirection * aSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
bg2.position += aDirection * aSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
bg3.position += aDirection * aSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;


Get the full code here: Scrolling 2d Background with Keypress Example


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s