MULTIMEDIA

Microsoft XNA Game Studio 3.0 : Getting Player Input - Using the Keyboard

2/24/2011 8:54:38 AM
XNA works with keyboards as well as with gamepads. You might be surprised to learn that you can plug a USB keyboard into an Xbox 360 and use it just as you’d use the keyboard on the PC. If you want the program to work with the keyboard, you can add code that does this, as shown here:
KeyboardState keys = Keyboard.GetState();

if (keys.IsKeyDown(Keys.R)) redIntensity++;
if (keys.IsKeyDown(Keys.B)) blueIntensity++;
if (keys.IsKeyDown(Keys.G)) greenIntensity++;
if (keys.IsKeyDown(Keys.Y))
{
redIntensity++;
greenIntensity++;
}

Note that the process is very similar to how the gamepad works, but there are slight differences. You don’t need to tell the GetState method on the Keyboard which keyboard to read because XNA supports only a single keyboard. The KeyboardState item that is returned from the call is not actually a piece of paper; instead, it is an object that provides methods that the program can use to discover whether a particular key is pressed. Rather than seeing if the state of a button is set to the value ButtonState.Pressed, the program can call the method IsKeyDown. You supply the IsKeyDown method with a parameter that identifies the key you are interested in, as follows:

if (keys.IsKeyDown(Keys.R)) redIntensity++;

This code is a conditional statement that increases the value of redIntensity if the R key is pressed. The method IsKeyDown returns true if the key is down and false if not. You can, therefore, use it to control the update of the redIntensity value.

1. Stopping the Game with the Escape Key

The Update method that is created when you make a new XNA game contains a test that checks the for the Back button on gamepad 1 and calls the Exit method to stop the game when the Back button is pressed. If you are using a keyboard instead of a gamepad you will not be able to press this button to stop the a game. You can add a test for the Escape key on the keyboard. This key is a "control" key, in that it does not actually relate to a printable character, but is designed to signal an action you want the program to take. Other control keys include the Enter key and the Backspace key. You can use the same IsKeyDown method to test for the Escape key.

if (keys.IsKeyDown(Keys.Escape)) Exit();

This code stops the game when the Escape key is pressed.

2. Using a Gamepad and a Keyboard at the Same Time

If you want to use a gamepad and a keyboard simultaneously, you have to test for both. This means that the Update method now looks like this:

protected override void Update(GameTime gameTime)
{
GamePadState pad1 = GamePad.GetState(PlayerIndex.One);

if (pad1.Buttons.Back == ButtonState.Pressed) Exit();
if (pad1.Buttons.B == ButtonState.Pressed) redIntensity++;
if (pad1.Buttons.X == ButtonState.Pressed) blueIntensity++;
if (pad1.Buttons.A == ButtonState.Pressed) greenIntensity++;
if (pad1.Buttons.Y == ButtonState.Pressed)
if (pad1.Buttons.B == ButtonState.Pressed) redIntensity++;
{
redIntensity++;
greenIntensity++;
}

KeyboardState keys = Keyboard.GetState();

if (keys.IsKeyDown(Keys.Escape)) Exit();

if (keys.IsKeyDown(Keys.R)) redIntensity++;
if (keys.IsKeyDown(Keys.B)) blueIntensity++;
if (keys.IsKeyDown(Keys.G)) greenIntensity++;
if (keys.IsKeyDown(Keys.Y))
{
redIntensity++;
greenIntensity++;
}
base.Update(gameTime);
}


This code is not good because you are doing the same thing twice, just triggered in a different way. The Great Programmer, if she ever saw this, would not be impressed. Fortunately C# provides a way that a program can combine two conditions and then perform some code if either condition is true. This way of combining conditions is called the OR logical operator because it is true if one thing or the other is true, and it is written in the program as two vertical bars (||):

GamePadState pad1 = GamePad.GetState(PlayerIndex.One);
KeyboardState keys = Keyboard.GetState();

if (pad1.Buttons.B == ButtonState.Pressed ||
keys.IsKeyDown(Keys.R)) redIntensity++;

The OR logical operator is placed between two Boolean expressions that can be either true or false. If one or the other expression is true, the combined logical condition works out to be true. In this code, if the red button is pressed on the gamepad or the R key is pressed on the keyboard (or both), the redIntensity value increases. This is exactly what you want, and it means that Color Nerve can now be played with the gamepad or the keyboard (or both at the same time). Logical operators are so called because they produce logical rather than numerical results. There are other logical operators that you will use as you create more complex programs.


Note:

If you find this logical operator stuff hard to understand, just go back to the problem that you are trying to solve. You want the program to perform a statement (redIntensity++) if the red key is pressed on the gamepad or if the R key is pressed on the keyboard. So you use the OR operator (||) to combine the two tests and make a condition that triggers if one or the other condition is true.



Note:

The sample project in the directory "02 Color Nerve" in the resources for this article implements the game. You can adjust the colors of the screen by pressing the gamepad buttons or a key on the keyboard.


Other  
  •  iPhone 3D Programming : Blending and Augmented Reality - Stencil Alternatives for Older iPhones
  •  iPhone 3D Programming : Blending and Augmented Reality - Poor Man’s Reflection with the Stencil Buffer
  •  Microsoft XNA Game Studio 3.0 : Getting Player Input - Reading a Gamepad
  •  iPhone 3D Programming : Blending and Augmented Reality - Shifting Texture Color with Per-Vertex Color
  •  iPhone 3D Programming : Blending and Augmented Reality - Blending Extensions and Their Uses
  •  iPhone 3D Programming : Blending and Augmented Reality - Blending Caveats
  •  Building LOB Applications : Using Visual Studio 2010 WCF RIA Data Services Tooling
  •  Building LOB Applications : Implementing CRUD Operations in WCF Data Services
  •  iPhone 3D Programming : Blending and Augmented Reality - Wrangle Premultiplied Alpha
  •  iPhone 3D Programming : Blending and Augmented Reality - Blending Recipe
  •  Microsoft XNA Game Studio 3.0 : Controlling Color (part 3)
  •  Microsoft XNA Game Studio 3.0 : Controlling Color (part 2)
  •  Microsoft XNA Game Studio 3.0 : Controlling Color (part 1) - Games and Classes & Classes as Offices
  •  Microsoft XNA Game Studio 3.0 : Working with Colors
  •  iPhone 3D Programming : Textures and Image Capture - Creating Textures with the Camera
  •  iPhone 3D Programming : Textures and Image Capture - Dealing with Size Constraints
  •  Programming with DirectX : Game Math - Vectors
  •  iPhone 3D Programming : Textures and Image Capture - Generating and Transforming OpenGL Textures with Quartz
  •  iPhone 3D Programming : Textures and Image Capture - The PowerVR SDK and Low-Precision Textures
  •  Building LOB Applications : Using Visual Studio 2010 WCF Data Services Tooling
  •  
    Most View
    Programming .NET Components : Building a Distributed Application (part 4) - Administrative Type Registration, Administrative Configuration Example
    ASP.NET 4 : Web Site Navigation (part 4) - Security Trimming, URL Mapping, URL Rewriting
    Introduction to Windows 8 Administration : Deploying Windows 8
    ADO.NET Programming : Microsoft SQL Server CE (part 4) - Updating a SQL Server CE Database, The SqlCeDataAdapter Class
    Processor Group Test (Part 4) - Intel Core i5-2500K
    Multimedia: Tips and Tricks – Feb 2013 (Part 2)
    Microsoft ASP.NET 4 : How MVC Plays with ASP.NET (part 2) - Following the Request Path - Implementing scenarios for adding, deleting, and updating
    A Click Away From Malware
    Make The Switch (Part 1)
    Programming Excel with VBA and .NET : Expressions, Exceptions
    Top 10
    10 Contenders For The 'Ultimate Protector' Crown (Part 5) : Microsoft Security Essentials 4.1, AVG Antivirus Free 2013
    10 Contenders For The 'Ultimate Protector' Crown (Part 4) : Norton Internet Security, Avast Free Antivirus Version 7
    10 Contenders For The 'Ultimate Protector' Crown (Part 3) : Eset Smart Security 6, Kaspersky Internet Security 2013, Zonealarm Internet Security 2013
    10 Contenders For The 'Ultimate Protector' Crown (Part 2) : Bitdefender Total Security 2013, Trend Micro Maximum Security, Mcafee Internet Security 2013
    10 Contenders For The 'Ultimate Protector' Crown (Part 1)
    Sony Xperia TL - Much Improved But Still Imperfect (Part 3)
    Sony Xperia TL - Much Improved But Still Imperfect (Part 2)
    Sony Xperia TL - Much Improved But Still Imperfect (Part 1)
    Simple.TV - Transmits TV Programs To Mobile (Part 2)
    Simple.TV - Transmits TV Programs To Mobile (Part 1)