Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm using XNA to create a simple block breaker game. At the moment I have controls set in the standard way:

if (keystate.IsKeyDown(Keys.s))

I've figured out the file handling problems involved and have taken in a string from a text box, for examples sake I'll have that string as "NumPad2". Now I need the game to take that string and somehow use "NumPad2" as the new control, instead of "s".

share|improve this question
add comment

2 Answers

up vote 7 down vote accepted

Just use Enum.Parse, something like this:

var key = (Keys) Enum.Parse(typeof(Keys), keyString);

where keyString = "NumPad2", as you declared previously

share|improve this answer
    
Brilliant. This is exactly what I was looking for. –  Matthew Morgan Mar 27 '13 at 10:48
    
@MatthewMorgan Ah, okay, I guess the wording of the question confused me. As a long-term solution, you should still consider using some kind of built-in serialization to store your settings. –  Marton Mar 27 '13 at 10:59
    
It might be better to use Enum.TryParse in the event that you want to do error handling without handling the exceptiont hat enum.parse would throw in the event of an invalid string value. –  Tetrad Mar 27 '13 at 22:09
add comment

Create an IXmlSerializable class that handles saving / loading of the key settings. For example:

public class ControlSettings : IXmlSerializable
{
   public Keys MoveUp;
   public Keys MoveDown;
   public Keys Shoot;

   public ControlSettings() {}
   //...
}

When you start the game, create a new instance of ControlSettings by deserializing an XML that defines the assigned keyboard controls (let's call this instance myControlSettings). Then in your game code:

if (keystate.IsKeyDown(myControlSettings.MoveUp))
{
   //...
}
share|improve this answer
    
I think the real important take away here, even though its kind of confusing since Keys is already used in XNA, is you should really map your inputs to actions (Shoot is the real hint at this) and have a class that performs the conversion between Inputs and Actions. This class could be created using the technique described in the other answer. –  SpartanDonut Mar 27 '13 at 17:04
    
@ToddersLegrande Yes, you're right, I'll edit the names of the Up and Down variables. –  Marton Mar 27 '13 at 22:00
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.