Getting Started with XNA Game Studio 3.0 to develop video games
Part V

This month we`ll discuss about the code and steps to use Keyboard and Mouse in a PC game.
Player inputs are one of the important thing in a Video game.

Help screen from NFS 6
First you need to have an image to represent mouse cursor and another image to show the keyboard usage.
You can add those files in to the content folder.

Then you are able to write a code to use keyboard and mouse.
In the Game1.cs file initialize these variables.
KeyboardState mykeyboardstate;
//create a keyboardstate object to get the state of the keyboard
MouseState mymousesatate;
//get the state of the mouse
SpriteFont myfont;
//add a sprite font to draw String in the screan
Texture2D mytexture, mytexture2;//creating texture object
float Position = 0.0f;//initializing up down position
float Position2 = 0.0f;//initializing left right position
float mousex = 0.0f;//initilizing mousex position
float mousey = 0.0f;//initializing mousey position
Now in the LoadContent()method write code for load the assest.
//change the window title
Window.Title = "Using the keyboard+mouse-demo";
myfont = Content.Load<SpriteFont>("Arial");
mytexture = Content.Load<Texture2D>("pic");
mytexture2 = Content.Load<Texture2D>("cursor");
Then in the Update() methord you can chack for keyboard and mouse inputs.
mykeyboardstate = Keyboard.GetState();//capturing the keybard state
mymousesatate = Mouse.GetState();//capturing mouse state
mousex = (float)mymousesatate.X;//getting the x position of the mouse
mousey = (float)mymousesatate.Y;//getting the y position of the mouse
// Move 400 pixels each second
float moveFactorPerSecond = 80 * (float)gameTime.ElapsedRealTime.TotalMilliseconds / 1000.0f;
//chage the position according to the key pressed up,down,left,right
if (mykeyboardstate.IsKeyDown(Keys.Up))
Position -= moveFactorPerSecond;
if (mykeyboardstate.IsKeyDown(Keys.Down))
Position += moveFactorPerSecond;
if (mykeyboardstate.IsKeyDown(Keys.Left))
Position2 -= moveFactorPerSecond;
if (mykeyboardstate.IsKeyDown(Keys.Right))
Position2 += moveFactorPerSecond;
In the Draw () method you can see the Changes of the inputs by drawing the images.
myspitebatch.Begin();//start process
Vector2 position = new Vector2(200.0f + (int)Position2, 200.0f + ((int)Position));
//setting position with variables (Position1) and (Position2)
//those variables change the position of the image according to the key pressing
myspitebatch.Draw(mytexture, position, Color.White);//drawing the image
myspitebatch.DrawString(myfont, "Use Arrowkeys to move the image&use mouse to point", new Vector2(10.0f, 10.0f), Color.Gold);//drawing text on the screan
myspitebatch.Draw(mytexture2, new Vector2(mousex, mousey), Color.White);
//drawing the cursor image, acording to the mouse position
myspitebatch.End();//end process
Now you can run the project by pressing F5 or by clicking the run button.

Final code of Game1.cs
/*
content created by -uditha sampath bandara
udithamail@yahoo.com
>
*/
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 Mouse_and_keyboard
{
///<summary>
/// This is the main type for your game
///</summary>
public class Game1 :Microsoft.Xna.Framework.Game
nbsp; {
GraphicsDeviceManager graphics;
SpriteBatch myspitebatch;
KeyboardState mykeyboardstate;
MouseState mymousesatate;
SpriteFont myfont;
Texture2D mytexture, mytexture2;
float Position = 0.0f;
float Position2 = 0.0f;
float mousex = 0.0f;
float mousey = 0.0f;
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()
{
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()
{
Window.Title = "Using the keyboard+mouse-demo";
myspitebatch = new SpriteBatch(GraphicsDevice);
myfont = Content.Load<SpriteFont>("Arial");
mytexture = Content.Load<Texture2D>("pic");
mytexture2 = Content.Load<Texture2D>("cursor");
}
///<summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
///</summary>
protected override void UnloadContent()
{
}
/// <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();
mykeyboardstate = Keyboard.GetState();
mymousesatate = Mouse.GetState();
mousex = (float)mymousesatate.X;
mousey = (float)mymousesatate.Y;
float moveFactorPerSecond = 80 *
(float)gameTime.ElapsedRealTime.TotalMilliseconds / 1000.0f;
if (mykeyboardstate.IsKeyDown(Keys.Up))
Position -= moveFactorPerSecond;
if (mykeyboardstate.IsKeyDown(Keys.Down))
Position += moveFactorPerSecond;
if (mykeyboardstate.IsKeyDown(Keys.Left))
Position2 -= moveFactorPerSecond;
if (mykeyboardstate.IsKeyDown(Keys.Right))
Position2 += moveFactorPerSecond;
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.Black);
myspitebatch.Begin();
Vector2 position = new Vector2(200.0f + (int)Position2, 200.0f + ((int)Position));
myspitebatch.Draw(mytexture, position, Color.White);
myspitebatch.DrawString(myfont, "Use Arrowkeys to move the image&use mouse to point", new Vector2(10.0f, 10.0f), Color.Gold);
myspitebatch.Draw(mytexture2, new Vector2(mousex, mousey), Color.White);
myspitebatch.End();
base.Draw(gameTime);
}
}
}
This is the end of the using Mouse and Keyboard in a PC game tutorial.
Also source project is attached with this article.
Form next tutorial you learn about working with game Menus in XNA.



Post new comment