XNA Sidescroller Part 2
Welcome to the second part of three tutorials (maybe 4, depending on how lazy I am). In this tutorial we will get the player moving around the map. Collision detection. I you haven’t done part one click the link above and take the tutorial, or just download the source files (link down the bottom of part 1) and continue where we left off.
First open the solution explorer (View > Solution Explorer) and right click on your project. Go to Add > New Item…
Select Class and call it Player.cs. We will put all our player related code in here to keep everything nice and clean. Click Add and you should get a new file looking like this:
using System.Collections.Generic;
using System.Text;
namespace SidescrollTutorial
{
class Player
{
}
}
Add these three using statement below the other three that are already there.
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
This just saves us from writing Microsoft.Xna.Framework before everything related to XNA. We need to add some properties and methods to the Player class. Three properties:
public Vector2 ScreenPosition;
private Texture2D texture;
private Vector2 speed;
MapPosition is the players position relative to the top left corner of the map. ScreenPosition is the players position relative to the top left corner of the games window and texture will be the players texture. ’speed’ is the players speed (duh). And three methods
{
}
public void LoadContent(Texture2D t)
{
texture = t;
}
public void Update(GameTime gameTime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
}
The first is the classes constructor, it has one parameter that will be the players spawn point. This is run every time a Player object is made. Next we have LoadContent. We will use this to load the players texture. The next two are Update and Draw like in Game1.cs.
Go back to Game1.cs. Find the line that says Texture2D playerTex. Underneath it add Player player;. Find Game1() and in it (doesn’t matter where) add player = new Player(new Vector2(32, 544));.
[32, 544] is the coordinates of the players spawn point. Now that we have a player object lets load its texture using LoadContent(). Find LoadContent() in Game1.cs and replace playerTex = Content.Load
Go down to the Update() method (still in Game1.cs) and add this bit of code above base.Update(gameTime);.
Now go down to the Draw() and above spriteBatch.End() add player.Draw(spriteBatch);.
Now there is only one more thing we have to do in Game1.cs for now. In the Draw() method find the for loop that draws the tiles. Replace it with this:
for(int j = 0; j < Levels.level0.GetLength(1); j++)
{
Vector2 tilePos = new Vector2(j * 32, i * 32);
Vector2 playerPos = player.ScreenPosition - player.MapPosition;
tilePos += playerPos;
if (Levels.level0[i, j] == 1)
spriteBatch.Draw(blackTileTex, tilePos, Color.White);
if (Levels.level0[i, j] == 2)
spriteBatch.Draw(redTileTex, tilePos, Color.White);
if (Levels.level0[i, j] == 3)
spriteBatch.Draw(yellowTileTex, tilePos, Color.White);
}
The way it was before worked if you didn’t want the map to scroll, but since we do want it to scroll we need to change it. So now each tile is drawn to the position it was before, plus the players screen position minus the players map position. Don’t ask me how it works. It just does.
Go back to Player.cs. Add this to the constructor (Player()).
ScreenPosition = new Vector2(400, 300);
We are just setting the Map and Screen Position.
Go down to Draw() and add this line:
We are drawing the player texture to [400,300]. The colour is set to white. If you set it to any other colour it will have a tinted that colour, which we don’t want.
If you press F5 to debug your project you should see that your player is being drawn in the middle of the screen, like below.
Just too make sure we are on the same page, your Player class should look like this:
{
public Vector2 MapPosition;
public Vector2 ScreenPosition;
private Texture2D texture;
private Vector2 speed;
public Player(Vector2 p)
{
MapPosition = p;
ScreenPosition = new Vector2(400, 300);
}
public void LoadContent(Texture2D t)
{
texture = t;
}
public void Update(GameTime gameTime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, ScreenPosition, Color.White);
}
}
Now all that’s left is to too get him moving. First we need a keyboard state, so we know when the user is pressing a key. Add private KeyboardState kbState; underneath the line private Vector2 speed;. Now scroll down to the Update method. Since this is run every frame we will put our movement code here. First we need to set kbState to the keyboards current state, so add kbState = Keyboard.GetState(); to the method. Underneath that add this bit of code:
speed.X = -300 * (float)gameTime.ElapsedGameTime.TotalSeconds;
else if (kbState.IsKeyDown(Keys.Right))
speed.X = 300 * (float)gameTime.ElapsedGameTime.TotalSeconds;
else
speed.X = 0;
This is what makes the player move. We have an if statement checking if the left arrow key is down. If it is it sets the X speed to -300 * (float)gameTime.ElapsedGameTime.TotalSeconds;. gameTime.ElapsedGameTime.TotalSeconds; is the amount of time it has been since the last frame. Multiplying 300 by this means that over 1 second the player will have moved 300 pixels to the left. This means 5 pixels a second if the fps is 60 (which it should be), or 10 pixels a second if the fps is 30. This means that even on a slow computer everything will still move at the same speed, it will just be moving faster less, instead of slower more (if that makes sense
).
The next couple of lines are just the same thing but for the right arrow key, and if neither of the keys are pressed speed.X is set to zero.
So we have this speed variable, but the players position isn’t changing. That’s because we need to add the speed variable to the players position. So underneath all the code you just added put this line: MapPosition += speed;.
Your update method should be looking like so:
{
kbState = Keyboard.GetState();
if (kbState.IsKeyDown(Keys.Left))
speed.X = -300 * (float)gameTime.ElapsedGameTime.TotalSeconds;
else if (kbState.IsKeyDown(Keys.Right))
speed.X = 300 * (float)gameTime.ElapsedGameTime.TotalSeconds;
else
speed.X = 0;
MapPosition += speed;
}
Now if you press F5 to debug your game you should see what you saw before, but if you press the arrows keys your player should move around (your player isn’t actually moving, the map is). He still goes through walls and he can’t jump, but we will save that for part 3.
Download source files. (.zip, 50kb)
If you enjoyed this tutorial please kick it.















Very nice tutorials keep them coming
Hey Awesty,
By any chance could you turn back to Flash for a little bit and maybe show us how to create our own isometric type game, where u click a square and it takes you there. Sort of like www.habbo.co.uk or www.bittybay.com ?
It would be greatly appreciated.
Sorry if this isn’t a good place to ask this, but I am really desperate.
Regards,
Calum
…or ignore me. -.-
Is XNA free? Please, I would apreciate it, thank you so much.
Xna is free for creating games that run on windows, but for creating games on the xbox 360
it requires a monthly subsciption.Which cost money.
But if your just starting out then download Xna and create games for windows.
I am not going to make any games for game cube and others. just for PCs.
So, where can I download it?
you can download xna at the following website:
Just click here to go to the site
Thanks…I just noticed, though, that I have to use a different kind of code. So I think I want to stick sith actionscript and then move on to a harder one later.
Thanks again!
no problem, anytime
Good luck.
Thanks!
Could you visit my blog:
eagleproductions.wordpress.com
yeah i’ll check it out
nice tut, I cant wait for the rest…
Awesty…its been long. Again.
I started my own blog:
http://eagleproductions.wordpress.com
Tell me what you think.
ACK!
I just noticed I already typed the blog thingy before…sorry
yea it has been long.
I(just like eagleVision) have created my own blog. Except that it will be similar to this.
As of right now i am working on a tut for making a small 3d engine. I am also working on some other tuts.
As of right now the site is useless but check it everynow and then for updates.
here is the site:
http://roosterproduction.wordpress.com/
Hi there!
I was given a school project to build a game with different levels, & the character to shoot enemies, collect items to gain points.
I found your website, followed your XNA C# tutorials and found them useful.
Could u post up tutorial for XNA Sidescroller Part 3?
Or more of the tutorials to complete the game?
If u are too busy to blog, perhaps u could send me an email with guides or steps to complete the game? bluishprawn@hotmail.com.
Need help. Thanks a lot!