Colombo 05, Sri Lanka
24-07-2010
Colombo, Sri Lanka
21-05-2010
Dehiwala, Sri Lanka
21-05-2010
Colombo, Sri Lanka
16-06-2010
Getting Started with XNA Game Studio 3.0 to develop video games



by Uditha
Sampath Bandara

This month we`ll dicuss about the code and steps to write your first hello world programe.

 After you load a XNA project to Visual studio solution explore looks like this.

 

 

 

In the Solution Explorer you can see two main c# class files,Program.cs and Game1.cs. Program.cs holds the main metord of the game.

Content folder contains all the graphic asserts in your game. It can  be 2d images ,3d models or sheder files.

 

 

Program.cs

using System;

 

namespace WindowsGame1

{

    static class Program

    {

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        static void Main(string[] args)

        {

            using (Game1 game = new Game1())

            {

                game.Run();

            }

        }

    }

}

 

game.Run() metord intilize the game class in you application.

 

Game1.cs file contains important method calls that are unique to XNA. If you're doing Windows from application ,you unable to see those type of method calls.

 

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;

 

 

In order to work with XNA API ,you need to use Microsoft.Xna.Framework namespaces.That contains Audio,Content, GamerServices, Graphics, Input,

Media,Net,Storage functionalities.

 

 

public class Game1 : Microsoft.Xna.Framework.Game

    {}

 

Our Game1 class is inheriting from the original XNA Framework Game class.

So we can have all the functionalities given in the XNA Framework Game Class.

 

public Game1()

        {

            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";

        }

this is the constucter of the games. And in this method call garphic device manager gets initilized and Sets the content folder.

 

 

protected override void Initialize()

        {

            // TODO: Add your initialization logic here

 

            base.Initialize();

        }

 

this method is use for initialize the variables ,when the game starts.As an example, if we want to set some default startup location when car game starts.

So we can use this method to do that.

 

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

        }

 

 

this metord is able to load the graphic conetnt to the vga card. So we need to specify all the 2d and 3d contetnt in this section.

Example –

myfont = Content.Load<SpriteFont>("Arial");


protected override void UnloadContent()

        {

            // TODO: Unload any non ContentManager content here

        }

 

 

 

this method able to unload the graphic content from the vga  card.

 


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);

        }

 

 

spriteBatch.DrawString(myfont, "Hello world", new Vector2(10.0f, 10.0f), Color.Black);using System;

This is one of the important methods in the Game class. In a windows form application when you call a certain method as finding the sum,in the GUI you need to click a button or do something similar to that. Then that method gets called once.

 

But update methord is not like that. It will call every 300 ms as a never ending 'for loop'. From that metord call, it will detect whether user press any key. Also it id used for write logic of the game.

So  you need to be careful think when you writing codes in that methord.

 

protected override void Draw(GameTime gameTime)

        {

            GraphicsDevice.Clear(Color.CornflowerBlue);

             // TODO: Add your drawing code here

             base.Draw(gameTime);

        }

 

This method is similar as the update method. It also calls in every 300 ms. And this method is using for draw 2d and 3d graphics.

You can do all the 2d and 3d rendering of the game in this method call.

 

Now I think you know the basic method calls and class structure of a XNA game.

All these codes are automatically generated when you load a windows game project.

 

Default Game1.cs file

 

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 WindowsGame1

{

    /// <summary>

    /// This is the main type for your game

    /// </summary>

    public class Game1 : Microsoft.Xna.Framework.Game

    {

        GraphicsDeviceManager graphics;

        SpriteBatch spriteBatch;

        SpriteFont myfont;

 

        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>

        protected override void LoadContent()

        {

            // Create a new SpriteBatch, which can be used to draw textures.

            spriteBatch = new SpriteBatch(GraphicsDevice);

            myfont = Content.Load<SpriteFont>("Arial");

 

            // 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();

 

            // 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

 

            base.Draw(gameTime);

        }

    }

}

 

 

 

To write a hello world game, first you need to load font to the content folder.

Right click on the content folder and Add->new item

 

 

 


And select Sprite font and rename that as  Arial.spritefont

Arial is the name of the font we are going to use.

You can use any font that install in the Windows font folder.

 


Go to Arial.spritefont file

if you like you can change the size and style by modifing Size and Style tags.

 

<Size>14</Size>

<Style>Regular</Style>

 

Final   Arial.spritefont  file.

 

<?xml version="1.0" encoding="utf-8"?>

<!--

This file contains an xml description of a font, and will be read by the XNA

Framework Content Pipeline. Follow the comments to customize the appearance

of the font in your game, and to change the characters which are available to draw

with.

-->

<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">

  <Asset Type="Graphics:FontDescription">

 

    <!--

    Modify this string to change the font that will be imported.

    -->

    <FontName>Kootenay</FontName>

 

    <!--

    Size is a float value, measured in points. Modify this value to change

    the size of the font.

    -->

    <Size>14</Size>

 

    <!--

    Spacing is a float value, measured in pixels. Modify this value to change

    the amount of spacing in between characters.

    -->

    <Spacing>0</Spacing>

 

    <!--

    UseKerning controls the layout of the font. If this value is true, kerning information

    will be used when placing characters.

    -->

    <UseKerning>true</UseKerning>

 

    <!--

    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",

    and "Bold, Italic", and are case sensitive.

    -->

    <Style>Regular</Style>

 

    <!--

    If you uncomment this line, the default character will be substituted if you draw

    or measure text that contains characters which were not included in the font.

    -->

    <!-- <DefaultCharacter>*</DefaultCharacter> -->

 

    <!--

    CharacterRegions control what letters are available in the font. Every

    character from Start to End will be built and made available for drawing. The

    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin

    character set. The characters are ordered according to the Unicode standard.

    See the documentation for more information.

    -->

    <CharacterRegions>

      <CharacterRegion>

        <Start> </Start>

        <End>~</End>

      </CharacterRegion>

    </CharacterRegions>

  </Asset>

</XnaContent>

 

 

Now in the Game 1.cs you need to write code to draw a string in the screan. Still we didn`t write any code in our game. Only did the renaming of fonts.

 

First create a object form SpriteFont to handle our font.

SpriteFont myfont;

Then in the LoadContent()  metord you can load the font.

 

myfont = Content.Load<SpriteFont>("Arial");

 

then in the Draw()metord you can draw the font in the sceran.

spriteBatch.Begin();   / /start the sprite batch process to draw font

 

//drawString() mathord is getting parameters for font type,string valuve,x and y positions in the screan where you need to put the string,and the font color.

 

                     //draw the font in the screan

 

spriteBatch.End();   //end the sprite batch process


now you can run the project by pressing F5 or by clicking the run button.


 Final code of Game1.cs

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 WindowsGame1

{

    /// <summary>

    /// This is the main type for your game

    /// </summary>

    public class Game1 : Microsoft.Xna.Framework.Game

    {

        GraphicsDeviceManager graphics;

        SpriteBatch spriteBatch;

        SpriteFont myfont;

 

        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>

        protected override void LoadContent()

        {

            // Create a new SpriteBatch, which can be used to draw textures.

            spriteBatch = new SpriteBatch(GraphicsDevice);

            myfont = Content.Load<SpriteFont>("Arial");

 

            // 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();

 

            // 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);

 

            spriteBatch.Begin();

            spriteBatch.DrawString(myfont, "Hello world", new Vector2(10.0f, 10.0f), Color.Black);

            spriteBatch.End();

 

            base.Draw(gameTime);

        }

    }}

 


 

This is the end of the First hello world program.

For this application it only took 5 lines of code.

If you are using unmanged c++ code to hello world programe it takes about 200 lines of code.

So its lot easier to develop XNA games using C#.

 

From next tutorial you learn about working with 2d graphics in XNA.

 

Uditha Sampath Bandara.

Lead game developer.

http://uditha.wordpress.com/

 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.