• Register

Reggae Speed is essentially a Driving/Racer genre Game, but it uses Carts instead of Cars and is set on a Jamican ambient in which the Player drives a Sled Cart with wheels. It features strong Gameplay Mechanics and Philosophy, an Intuitive Control System and a Physics Based Driving System to create a Game you won't forget you Played!

Post tutorial Report RSS Creating a Simple 2D Game with XNA 1: Basic Rendering and Input

How to create a simple 2D Game with XNA. In this tutorial, you'll learn how to render images to the screen and control them with basic keyboard input.

Posted by on - Intermediate Client Side Coding

Hey there! I've been meaning to make a tutorial series on programming for XNA Game Studio, an extremely popular and cross-platform game engine which allows you to write games for the Windows PC, Xbox 360 and Zune Media-Player. XNA games are all programmed in C#, which is a suprisingly simple language to learn. Although no previous experience with XNA is required for these tutorials, some experience with C# or just programming in general may help with your understanding, though I will guide you through every line of code you write.


XNA Game Studio is a great first-time game programming library

Before you get started, make sure you have a copy of Microsoft Visual C# and, of course, XNA Game Studio (the latest stable version is 3.1). You can download Visual C# here and XNA 3.1 here, and follow the setup instructions. There are plenty of XNA installation tutorials out there, and I don't want to waste time reinventing the wheel telling you how to install XNA.

Once you have all the software you need, you can get started!

1. Open up Visual C#. Go to File and then click 'New Project'. Select 'XNA Game Studio 3.1' in the 'Project Types' panel on the left, make sure 'Windows Game (3.1)' is selected, then type in a suitable name for the project e.g. 'MyFirstXNAGame' and hit OK.


This is how you start a new XNA Game Project in Visual C#

2. Visual C# will now auto-generate everything you need for a basic XNA Windows game. Once it has auto-generated the project, you will see a big mess of code appear. You can try running this by clicking the green 'play' button at the top, and you should see a blue-shaded window appear. This is your main game window, and it is the window in which you can render graphics and receive input, the basis of any 2D game. Close it, and we can begin with the programming!


The basic blue-shaded XNA Window

3. Now, you will need to import content and resources into your project before you start coding. Game resources include images, sprites, sounds files, animation files etc. For this tutorial, we will only be using 1 image to display on screen and interact with. Right click the 'Content' icon in the Solution Explorer Panel (normally found on the right of the screen, if you cannot see it, click 'View' and then 'Solution Explorer'), then go to 'Add' and then 'Existing Item'. Now, locate an image file on your disk (.jpg, .bmp, .png, .gif all work fine with XNA)


How you add content to your XNA Game

4. Now we can start actually coding game behaviour. Scroll down the auto-generated program until you find a code segment starting with 'protected override void LoadContent()'. It should look something like this:

csharp code:
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

Now, modify it so that it looks like this:

csharp code:
        Texture2D MySprite;
        Vector2 MySpritePosition = Vector2.Zero;

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            MySprite = Content.Load<Texture2D>("apple");

            // TODO: use this.Content to load your game content here
        }

Except that where I've written "apple" you should insert the name of the image file you imported into the project, except without the file extension. For instance, if you imported an image file called 'pigeon.png', the code would look like:

csharp code:
MySprite = Content.Load<Texture>("pigeon");

The 'Texture2D' is a Texture which can be displayed directly onto the screen, and the 'Vector2' is the vector storing the position of where the texture will be displayed. The code is simply importing an image file into the Texture2D so that it can later be displayed onto the screen.

5. So we've added the code to load our game content, but what about rendering it? Next we want to add our render code, so scroll down the program until you find the code segment starting with 'protected override void Draw(GameTime gameTime)'. It should look like this:

csharp code:
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }

Now you want to add the render code so the code segment looks like this:

csharp code:
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            spriteBatch.Begin();
            spriteBatch.Draw(MySprite, MySpritePosition, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }

This code will render the Texture2D to the screen in the form of a SpriteBatch, an easy way of rendering basic 2D graphics to the screen.

Now, we have our basic framework completed! You can actually run your game to see how it looks, by clicking the green 'play' button at the top again. You should see the same blue window as before, but now with your image displayed in the top left corner!


Your image is rendered on screen!

6. As our final step, we want to add the ability to move our object using keyboard input. In this example, I will add the code required to move our image using the 'W' 'S' 'A' and 'D' keys, although you can modify the code later to fit whatever keys you want. Scroll to the code segment which starts with 'protected override void Update(GameTime gameTime)' which should read:

csharp code:
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

Then add the keyboard code so the segment looks like this:

csharp code:
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            KeyboardState keyboard = Keyboard.GetState();
            if (keyboard.IsKeyDown(Keys.W)) { MySpritePosition.Y -= 5; }
            if (keyboard.IsKeyDown(Keys.S)) { MySpritePosition.Y += 5; }
            if (keyboard.IsKeyDown(Keys.A)) { MySpritePosition.X -= 5; }
            if (keyboard.IsKeyDown(Keys.D)) { MySpritePosition.X += 5; }

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

This code receives input from the keyboard every frame, and updates your image texture's vector (or position) if the user holds down any of the 'W' 'S' 'A' and 'D' keys.


It's difficult to show movement in an image, but this is me controlling an image with the WSAD keys.

Congratz, you have completed this tutorial! Run your game one final time, and admire your work! The blue window will appear, your image will be displayed, and you can control it with the WSAD keys.

In case you got lost somewhere in this tutorial, here's the full source code of the game we just made (obviously, you still must change "apple" to whatever image file you wanted to display, minus the file extension):

csharp code:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace MyFirstXNAGame
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        ///
        Texture2D MySprite;
        Vector2 MySpritePosition = Vector2.Zero;

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            MySprite = Content.Load<Texture2D>("apple");

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            KeyboardState keyboard = Keyboard.GetState();
            if (keyboard.IsKeyDown(Keys.W)) { MySpritePosition.Y -= 5; }
            if (keyboard.IsKeyDown(Keys.S)) { MySpritePosition.Y += 5; }
            if (keyboard.IsKeyDown(Keys.A)) { MySpritePosition.X -= 5; }
            if (keyboard.IsKeyDown(Keys.D)) { MySpritePosition.X += 5; }

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            spriteBatch.Begin();
            spriteBatch.Draw(MySprite, MySpritePosition, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
 

Stay tuned for Part II of the XNA Programming Tutorial Series!

Post comment Comments
a157thhokage
a157thhokage

does this work for making games for Windows Phone 7 as well?

Reply Good karma Bad karma+2 votes
Morpheus22 Author
Morpheus22

It should work, as I know that XNA is natively compatible with the Windows Phone architecture, but the code will be quite different to this Windows PC game (the controls, screen-resolution etc. will be different) I will post another tutorial with instructions on how to write XNA code for embedded hardware, such as the Xbox, Zune Media Player and Windows Phone soon.

Reply Good karma+1 vote
Guest
Guest

It does but will require a separate IDE specially for Windows Phone development.

Reply Good karma Bad karma+1 vote
Guest
Guest

This comment is currently awaiting admin approval, join now to view.

bigdogdylan00
bigdogdylan00

I'm not sure if you can help me, but I get this error when I try to make a windows game 4.0 (vs2013):
A problem was encountered creating the sub project 'WindowsGame3'. The imported project "C:\Program Files (x86)\MSBuild\Microsoft\XNA Game Studio\Microsoft.Xna.GameStudio.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
(this was my comment originally.)

Reply Good karma Bad karma+1 vote
Guest
Guest

This comment is currently awaiting admin approval, join now to view.

Guest
Guest

This comment is currently awaiting admin approval, join now to view.

Post a comment

Your comment will be anonymous unless you join the community. Or sign in with your social account: