Xbox LIVE Indie Games
Sort Discussions: Previous Discussion Next Discussion
Page 1 of 1 (12 posts)

Converting Keyboard to Xbox Controller?

Last post 3/1/2010 2:17 PM by Meta. 11 replies.
  • 2/16/2010 12:46 PM

    Converting Keyboard to Xbox Controller?

    I'm new to programming and i wrote pong in xna but im trying to convert it to Xbox 360 and i cant find the controller, keyboard equivalents anywhere could someone explain this to me
  • 2/16/2010 1:04 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    There are no "equivalents", just different methods of input... You can poll each button, thumbstick and trigger on the gamepad and use that for input.

    If you're asking how to poll it, see here and here.
  • 2/17/2010 12:32 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    Basically i have pong working so that the arrow keys control one paddle and w and s keys controlling the other and i want to convert it so i can put it on to my xbox and play with a controller i already have it in xbox format in visual stuido but i need to change some of the code to get the controllers to work
  • 2/17/2010 1:15 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    Using the controller is not so much different from using the keyboard.

    For keyboard you usually do something like:

    KeyboardState kbState = Keyboard.GetState();
    if (kbState.IsKeyDown(Keys.W))
    // move paddle up


    While for gamepad you'd do:

    GamePadState gpState = GamePad.GetState(PlayerIndex.One);
    if (gpState.Buttons.DPadUp == ButtonState.Pressed)
    // move paddle up


    That's more or less it in a nutshell. If you work with gamepads though, at some point you will want to detect if the controller's still connected, and which controller the player uses and read from that controller and not PlayerIndex.One by default.

    But the simple code above shows the similarity between reading from keyboard and reading from gamepad.

    Hope it helped somewhat,

    Aya
  • 2/17/2010 1:53 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    I had to do it too.. here is how I made it work

    I created a class named LocalControls, so in my game I check with this class for any inputs

    this class look for the 4 gamepads, if not and XBOX, it will look for the first gamepad to see if it is connected, if not, it will "translate" the buttons to corresponding keys.

    here is the code
    PS: the big part is -> protected virtual Keys getAssociatedKey(Buttons button) { }

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using Microsoft.Xna.Framework; 
    using Microsoft.Xna.Framework.Input; 
     
    namespace DEMO_LocalControls 
        public class LocalControls : Microsoft.Xna.Framework.GameComponent 
        { 
            // All 4 Game Pads of the XBOX 
            protected GamePadState[] previousGamePadStates = new GamePadState[4]; 
            protected GamePadState[] currentGamePadStates = new GamePadState[4]; 
     
     
            // Keyboards states for Windows Support 
            protected KeyboardState previousKeyboardState; 
            protected KeyboardState currentKeyboardState; 
     
     
            // Mouse states for Windows Support 
            protected MouseState previousMouseState; 
            protected MouseState currentMouseState; 
     
            public Vector2 previousMousePosition() { return new Vector2( previousMouseState.X, previousMouseState.Y ); } 
            public Vector2 currentMousePosition() { return new Vector2( currentMouseState.X, currentMouseState.Y ); } 
     
            // For Acceleration, Deceleration, Time Tracking 
            protected GameTime lastGameTime; 
            #region CONSTRUCTOR 
     
            public LocalControls(Game game) 
                : base( game ) 
            { 
                // We want to be updated first ! 
                UpdateOrder = 1; 
     
                // Initiate our GamePads 
                previousGamePadStates = getGamePadStates(); 
                currentGamePadStates = previousGamePadStates; 
     
                // Initiate the keyboard State 
                previousKeyboardState = Keyboard.GetState(); 
                currentKeyboardState = previousKeyboardState; 
     
                // It will update with the game 
                game.Components.Add( this ); 
            } 
     
            public override void Initialize() 
            { 
                base.Initialize(); 
            } 
            #endregion 
            #region GAME PAD STATES 
     
            /// <summary> 
            /// Collect the 4 GamePad states 
            /// </summary> 
            /// <returns>An array of the 4 GamePadState</returns> 
            protected GamePadState[] getGamePadStates() 
            { 
                // Build an array for the 4 GamePads 
                GamePadState[] currentGamePadStates = new GamePadState[4]; 
     
                // Get the actual state of each GamePads 
                currentGamePadStates[0] = GamePad.GetState( PlayerIndex.One ); 
                currentGamePadStates[1] = GamePad.GetState( PlayerIndex.Two ); 
                currentGamePadStates[2] = GamePad.GetState( PlayerIndex.Three ); 
                currentGamePadStates[3] = GamePad.GetState( PlayerIndex.Four ); 
     
                // Return those actual states 
                return currentGamePadStates; 
            } 
     
     
            /// <summary> 
            /// Refresh all the 4 GamePad states 
            /// Called by Update( GameTime gameTime ); 
            /// </summary> 
            private void RefreshGamePad() 
            { 
                // Save them for later comparison 
                previousGamePadStates = currentGamePadStates; 
     
                // Actual states 
                currentGamePadStates = getGamePadStates(); 
            } 
     
     
            /// <summary> 
            /// Tells you if the button of that specified player had been pressed 
            /// </summary> 
            /// <param name="playerIndex">The index of the GamePad we want to check</param> 
            /// <param name="button">The button we want to check</param> 
            /// <returns>If this button is held down</returns> 
            public bool IsButtonPressed(PlayerIndex playerIndex, Buttons button) 
            { 
                if ( KeyboardNeeded( playerIndex ) ) 
                {   // The first player will be keyboard if no GamePad 
     
                    // Return if the key associated with this button had been pressed down 
                    return IsKeyboardKeyPressed( button ); 
                } 
                // Return if the button of the specified player had been pressed down 
                return currentGamePadStates[(int)playerIndex].IsButtonDown( button ) && previousGamePadStates[(int)playerIndex].IsButtonUp( button ); 
            } 
     
     
            /// <summary> 
            /// Tells you if the button of that specified player had been pressed 
            /// </summary> 
            /// <param name="playerIndex">The index of the GamePad we want to check</param> 
            /// <param name="button">The button we want to check</param> 
            /// <returns>If this button is held down</returns> 
            public bool IsButtonReleassed(PlayerIndex playerIndex, Buttons button) 
            { 
                if ( KeyboardNeeded( playerIndex ) ) 
                {   // The first player will be keyboard if no GamePad 
     
                    // Return if the key associated with this button had been pressed down 
                    return IsKeyboardKeyReleased( button ); 
                } 
                // Return if the button of the specified player had been pressed down 
                return currentGamePadStates[(int)playerIndex].IsButtonUp( button ) && previousGamePadStates[(int)playerIndex].IsButtonDown( button ); 
            } 
     
     
            /// <summary> 
            /// Tells you if the button of that specified player is held down 
            /// </summary> 
            /// <param name="playerIndex">The index of the GamePad we want to check</param> 
            /// <param name="button">The button we want to check</param> 
            /// <returns>If this button is held down</returns> 
            public bool IsButtonHold(PlayerIndex playerIndex, Buttons button) 
            { 
                if ( KeyboardNeeded( playerIndex ) ) 
                {   // The first player will be keyboard if no GamePad 
     
                    // Return if the key associated with this button is been hold 
                    return IsKeyboardKeyHold( button ); 
                } 
     
                // Return if the button of the specified player is hold down 
                return currentGamePadStates[(int)playerIndex].IsButtonDown( button ) && previousGamePadStates[(int)playerIndex].IsButtonDown( button ); 
            } 
     
     
            /// <summary> 
            /// Tells you if the specified GamePad is connected. 
            /// If you want player One under windows and no gamepad are connected, it return True because the keyboard will handle it 
            /// </summary> 
            /// <param name="index">Index of the desired GamePad</param> 
            /// <returns>If this specified GamePad is connected</returns> 
            public bool IsGamePadConnected(PlayerIndex playerIndex) 
            { 
                if ( KeyboardNeeded( playerIndex ) ) 
                {   // The first player will be keyboard if no GamePad 
                    return true
                } 
     
                // Return the IsConnected state of the specified GamePad 
                return currentGamePadStates[(int)playerIndex].IsConnected; 
            } 
            #endregion 
            #region Left ThumbStick 
     
            /// <summary> 
            /// Getting the X-Axis value 
            /// </summary> 
            /// <param name="playerIndex">Player we want to get info from</param> 
            /// <returns>X-Axis value</returns> 
            public virtual float getXAxis(PlayerIndex playerIndex) 
            { 
                float X = 0; 
                if ( KeyboardNeeded( playerIndex ) ) 
                {   // The first player will be keyboard if no GamePad 
     
                    // Validate to avoid the two opposite keys pressed ( left + right) 
                    if ( IsKeyboardKeyPressed( Buttons.LeftThumbstickLeft ) && IsKeyboardKeyPressed( Buttons.LeftThumbstickRight ) ) 
                    {   // The two oppoisites keys are pressed 
     
                        // return 0 
                        return 0; 
                    } 
     
                    bool isLeft, isRight; 
                    isLeft = IsKeyboardKeyHold( Buttons.LeftThumbstickLeft ); 
                    isRight = IsKeyboardKeyHold( Buttons.LeftThumbstickRight ); 
     
                    // Check if the axis is used 
                    if ( isLeft || isRight ) 
                    {   // One of the keys associated with the leftThumbStick X axis are held down 
     
                        // If CTRL is down, cut by half the value 
                        X = currentKeyboardState.IsKeyDown( Keys.RightControl ) ? 0.5f : 1f; 
     
                        // If Right is pressed, return a positive value otherwise it means that left is pressed, return a negative value 
                        return isRight ? X * 1 : X * -1; 
                    } 
     
                    // We are not moving at all, but there is room for deceleration here ! 
                    return X; 
                } 
                else 
                { 
                    return currentGamePadStates[(int)playerIndex].ThumbSticks.Left.X; 
                } 
            } 
     
     
            /// <summary> 
            /// Getting the Y-Axis value 
            /// </summary> 
            /// <param name="playerIndex">Player we want to get info from</param> 
            /// <returns>Y-Axis value</returns> 
            public virtual float getYAxis(PlayerIndex playerIndex) 
            { 
                float Y = 0; 
                if ( KeyboardNeeded( playerIndex ) ) 
                {   // The first player will be keyboard if no GamePad 
     
                    // Validate to avoid the two opposite keys pressed ( Up + Down) 
                    if ( IsKeyboardKeyPressed( Buttons.LeftThumbstickUp ) && IsKeyboardKeyPressed( Buttons.LeftThumbstickDown ) ) 
                    {   // The two oppoisites keys are pressed 
     
                        // return 0 
                        return 0; 
                    } 
     
                    bool isUp, isDown; 
     
                    isUp = IsKeyboardKeyHold( Buttons.LeftThumbstickUp ); 
                    isDown = IsKeyboardKeyHold( Buttons.LeftThumbstickDown ); 
     
     
                    // Check if the axis is used 
                    if ( isUp || isDown ) 
                    {   // One of the keys associated with the leftThumbStick Y axis are held down 
     
                        // If CTRL is down, cut by half the value 
                        Y = currentKeyboardState.IsKeyDown( Keys.RightControl ) ? 0.5f : 1f; 
     
                        // If Right is pressed, return a positive value otherwise it means that left is pressed, return a negative value 
                        return isDown ? Y * -1 : Y * 1; 
                    } 
     
                    // We are not moving at all, but there is room for deceleration here ! 
                    return Y; 
                } 
                else 
                { 
                    return currentGamePadStates[(int)playerIndex].ThumbSticks.Left.Y; 
                } 
            } 
     
            /// <summary> 
            /// Will return the left ThumbStick axis values 
            /// the Z of the vector3 is 0 or 1 depending if the stick was pressed 
            /// </summary> 
            /// <param name="playerIndex">The desired GamePad ID</param> 
            /// <returns>The axis + the stick button state</returns> 
            public Vector3 GetLeftThumbstickValues(PlayerIndex playerIndex) 
            { 
                return new Vector3(  
                    currentGamePadStates[(int)playerIndex].ThumbSticks.Left.X,  
                    currentGamePadStates[(int)playerIndex].ThumbSticks.Left.Y,  
                    currentGamePadStates[(int)playerIndex].Buttons.LeftStick == ButtonState.Pressed ? 1 : 0 
                ); 
            } 
            #endregion 
            #region Triggers / MouseWheel 
     
            public float GetCombinedTriggers(PlayerIndex playerIndex) 
            { 
                return GetRightTrigger( playerIndex ) - GetLeftTrigger( playerIndex ); 
            } 
     
            public float GetLeftTrigger(PlayerIndex playerIndex) 
            { 
                return currentGamePadStates[(int)playerIndex].Triggers.Left; 
            } 
     
            public float GetRightTrigger(PlayerIndex playerIndex) 
            { 
                return currentGamePadStates[(int)playerIndex].Triggers.Right; 
            } 
     
            public int GetMouseWheel() 
            { 
                return currentMouseState.ScrollWheelValue; 
            } 
            #endregion 
            #region KEYBOARD 
     
            /// <summary> 
            /// Will return a Keys object associated with the button pressed 
            /// This method can be override to use a different mapping 
            /// </summary> 
            /// <param name="button">The GamePadButton pressed</param> 
            /// <returns>the Key asociated with</returns> 
            protected virtual Keys getAssociatedKey(Buttons button) 
            { 
                // The key associated with the button 
                Keys k = Keys.Home; 
     
                switch ( button ) 
                {   // Associate with a GamePadButton 
                    #region 4 buttons 
     
                    case Buttons.X: 
                        // A on keyboard 
                        k = Keys.A; 
                        break
     
     
                    case Buttons.Y: 
                        // W on keyboard 
                        k = Keys.W; 
                        break
     
     
                    case Buttons.A: 
                        // S on keyboard 
                        k = Keys.S; 
                        break
     
     
                    case Buttons.B: 
                        // D on keyboard 
                        k = Keys.D; 
                        break
                    #endregion 
                    #region Shoulders 
     
                    case Buttons.LeftShoulder: 
                        // LeftShift on keyboard 
                        k = Keys.LeftShift; 
                        break
     
     
                    case Buttons.RightShoulder: 
                        // LeftShift on keyboard 
                        k = Keys.RightShift; 
                        break
                    #endregion 
                    #region LeftThumbStick 
     
                    case Buttons.LeftThumbstickDown: 
                        // DOWN 
                        k = Keys.Down; 
                        break
     
     
                    case Buttons.LeftThumbstickLeft: 
                        // LEFT 
                        k = Keys.Left; 
                        break
     
     
                    case Buttons.LeftThumbstickRight: 
                        // RIGHT 
                        k = Keys.Right; 
                        break
     
     
                    case Buttons.LeftThumbstickUp: 
                        // UP 
                        k = Keys.Up; 
                        break
                    #endregion 
                    #region DPAD 
     
                    case Buttons.DPadDown: 
                        // 2 on NumPad 
                        k = Keys.NumPad2; 
                        break
     
     
                    case Buttons.DPadUp: 
                        // 8 on NumPad 
                        k = Keys.NumPad8; 
                        break
     
     
                    case Buttons.DPadLeft: 
                        // 4 on NumPad 
                        k = Keys.NumPad4; 
                        break
     
     
                    case Buttons.DPadRight: 
                        // 6 on NumPad 
                        k = Keys.NumPad6; 
                        break
                    #endregion 
     
     
                    case Buttons.Back: 
                        // Back = Cancel/Exit -> Escape on keyboard 
                        k = Keys.Escape; 
                        break
                } 
     
                // return the key associated 
                return k; 
            } 
     
             
            /// <summary> 
            /// Will get the new state of the keyboard 
            /// </summary> 
            private void RefreshKeyboard() 
            { 
                // Save them for later comparison 
                previousKeyboardState = currentKeyboardState; 
                previousMouseState = currentMouseState; 
     
                // Actual states 
                currentKeyboardState = Keyboard.GetState(); 
                currentMouseState = Mouse.GetState(); 
            } 
     
     
            /// <summary> 
            /// Tells you if the key associated with this button is pressed down 
            /// </summary> 
            /// <param name="button">The button wanted</param> 
            /// <returns>If the key is pressed down</returns> 
            protected bool IsKeyboardKeyDown(Buttons button) 
            { 
                // Get the key related to this button 
                Keys k = getAssociatedKey( button ); 
     
     
                if ( k == Keys.S ) 
                {   // Jump/Action button is associated with left Mouse Button 
     
                    // If Left Mouse Button is pressed 
                    bool isClicked = currentMouseState.LeftButton == ButtonState.Pressed; 
     
                    // Return one or the other 
                    return currentKeyboardState.IsKeyDown( k ) || isClicked; 
                } 
     
     
                if ( k == Keys.D ) 
                {   // Combine button is associated with right Mouse Button 
     
                    // If Left Mouse Button is pressed 
                    bool isClicked = currentMouseState.RightButton == ButtonState.Pressed; 
     
                    // Return one or the other 
                    return currentKeyboardState.IsKeyDown( k ) || isClicked; 
                } 
     
     
                return currentKeyboardState.IsKeyDown( k ); 
            } 
     
     
            /// <summary> 
            /// Tells you if the key associated with this button has just being pressed down 
            /// </summary> 
            /// <param name="button">The button wanted</param> 
            /// <returns>If the key has just being pressed down</returns> 
            protected bool IsKeyboardKeyPressed(Buttons button) 
            { 
                // Get the key related to this button 
                Keys k = getAssociatedKey( button ); 
     
     
                if ( k == Keys.S ) 
                {   // Jump/Action button is associated with left Mouse Button 
     
                    // If Left Mouse Button was just pressed 
                    bool wasClicked = ( currentMouseState.LeftButton != previousMouseState.LeftButton ) && ( currentMouseState.LeftButton == ButtonState.Pressed ); 
     
                    // Return one or the other 
                    return ( currentKeyboardState.IsKeyDown( k ) && previousKeyboardState.IsKeyUp( k ) ) || wasClicked; 
                } 
     
     
                if ( k == Keys.D ) 
                {   // Combine button is associated with right Mouse Button 
     
                    // If Left Mouse Button was just pressed 
                    bool wasClicked = ( currentMouseState.RightButton != previousMouseState.RightButton ) && ( currentMouseState.RightButton == ButtonState.Pressed ); 
     
                    // Return one or the other 
                    return ( currentKeyboardState.IsKeyDown( k ) && previousKeyboardState.IsKeyUp( k ) ) || wasClicked; 
                } 
     
     
                return currentKeyboardState.IsKeyDown( k ) && previousKeyboardState.IsKeyUp( k ); 
            } 
     
     
            /// <summary> 
            /// Tells you if the key associated with this button was just released 
            /// </summary> 
            /// <param name="button">The button wanted</param> 
            /// <returns>If the key was just released</returns> 
            protected bool IsKeyboardKeyReleased(Buttons button) 
            { 
                // Get the key related to this button 
                Keys k = getAssociatedKey( button ); 
     
     
                if ( k == Keys.S ) 
                {   // Jump/Action button is associated with left Mouse Button 
     
                    // If Left Mouse Button was just pressed 
                    bool wasReleased = ( currentMouseState.LeftButton != previousMouseState.LeftButton ) && ( currentMouseState.LeftButton == ButtonState.Released ); 
     
                    // Return one or the other 
                    return ( currentKeyboardState.IsKeyUp( k ) && previousKeyboardState.IsKeyDown( k ) ) || wasReleased; 
                } 
     
     
                if ( k == Keys.D ) 
                {   // Combine button is associated with right Mouse Button 
     
                    // If Left Mouse Button was just pressed 
                    bool wasReleased = ( currentMouseState.RightButton != previousMouseState.RightButton ) && ( currentMouseState.RightButton == ButtonState.Released ); 
     
                    // Return one or the other 
                    return ( currentKeyboardState.IsKeyUp( k ) && previousKeyboardState.IsKeyDown( k ) ) || wasReleased; 
                } 
     
     
                return currentKeyboardState.IsKeyUp( k ) && previousKeyboardState.IsKeyDown( k ); 
            } 
     
     
            /// <summary> 
            /// Tells you if the key associated with this button is hold down 
            /// </summary> 
            /// <param name="button">The button wanted</param> 
            /// <returns>If the key is held down</returns> 
            protected bool IsKeyboardKeyHold(Buttons button) 
            { 
                // Get the key related to this button 
                Keys k = getAssociatedKey( button ); 
     
                if ( k == Keys.S ) 
                {   // Jump/Action button is associated with left Mouse Button 
     
                    // If Left Mouse Button is pressed 
                    bool isClicked = currentMouseState.LeftButton == ButtonState.Pressed; 
     
                    // Return one or the other 
                    return currentKeyboardState.IsKeyDown( k ) || isClicked; 
                } 
     
     
                if ( k == Keys.D ) 
                {   // Combine button is associated with right Mouse Button 
     
                    // If Left Mouse Button is pressed 
                    bool isClicked = currentMouseState.RightButton == ButtonState.Pressed; 
     
                    // Return one or the other 
                    return currentKeyboardState.IsKeyDown( k ) || isClicked; 
                } 
     
     
                return currentKeyboardState.IsKeyDown( k ) && previousKeyboardState.IsKeyDown( k ); 
            } 
     
     
            /// <summary> 
            /// Verify if we are under XBOX  
            /// If we are NOT under XBOX, the playerIndex is One and the GamePad One is not connected, we need a keyboard 
            /// No need of keyboard for all others players 
            /// </summary> 
            /// <param name="playerIndex">The index of the player</param> 
            /// <returns>If we need a keyboard support</returns> 
            protected virtual bool KeyboardNeeded(PlayerIndex playerIndex) 
            { 
    #if !XBOX 
                if ( playerIndex == PlayerIndex.One ) 
                {   // We are asking for the first player 
     
                    // We need a keyboard if no gamePad is connected 
                    return !currentGamePadStates[0].IsConnected; 
     
                } 
                else 
                {   // No need of gamepad for other players than the first 
                    return false
                } 
    #else 
                return false
    #endif 
            } 
            #endregion 
            
            #region UPDATE 
     
            public override void Update(GameTime gameTime) 
            { 
                // Keep track of the GameTime 
                this.lastGameTime = gameTime; 
     
                // Refresh the GamePadStates 
                RefreshGamePad(); 
     
     
                // For Windows Support 
                if ( KeyboardNeeded( PlayerIndex.One ) ) 
                {   // We need a keyboard for the player One because no GamePad is connected and we are not in a XBOX game 
                    RefreshKeyboard(); 
                } 
     
     
                // Base Call 
                base.Update( gameTime ); 
     
            } 
            #endregion 
        } 
     

    Feel free to use it, here how you add it into a game
    namespace DEMO_LocalControls 
        /// <summary> 
        /// This is the main type for your game 
        /// </summary> 
        public class DEMO : Microsoft.Xna.Framework.Game 
        { 
            GraphicsDeviceManager graphics; 
            SpriteBatch spriteBatch; 
     
            // Your controls 
            LocalControls controls; 
     
            public DEMO() 
            { 
                graphics = new GraphicsDeviceManager( this ); 
                Content.RootDirectory = "Content"
     
                // Creating the new GameComponent 
                controls = new LocalControls( this ); 
            } 
    ... 


    this will have the same effect, but it will also accept the "Esc" key ;-)

                // Allows the game to exit 
                if ( controls.IsButtonHold( PlayerIndex.One, Buttons.Back ) ) 
                    this.Exit(); 
     
                // Allows the game to exit 
                if ( GamePad.GetState( PlayerIndex.One ).Buttons.Back == ButtonState.Pressed ) 
                    this.Exit(); 
     



  • 2/19/2010 12:37 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    GamePadState

     

    gpState = GamePad.GetState(PlayerIndex.One);

     

    UpArrow = KeyboardInput.(

    Keys.Up);

     

    DownArrow = KeyboardInput.IsKeyDown(

    Keys.Down);

     

    WKey = KeyboardInput.IsKeyDown(

    Keys.W);

     

    SKey = KeyboardInput.IsKeyDown(

    Keys.S);

     

    random =

    new Random();

     

    BallSpeedx = random.Next(4, 8);

    BallSpeedy = random.Next(-8, 4);

    PlayAgainString =

    "Play Again?";

     

    mouse =

    Mouse.GetState();

     

    mousex = mouse.X;

    mousey = mouse.Y;





    here is the code i have i already chamged the first line but then do i just change the rest to the corresponding buttons on the xbox controller or does it stay the same and visual studio changes it already I'm not to sure because i havent done too much with xbox yet. thanks
  • 2/20/2010 5:56 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    I think the best way is to use #if(XBOX360)  etc statements, for example

    #if(!XBOX360) 
                if (keyboard.IsKeyDown(Keys.A)) 
    #else 
                if (gamePad.IsButtonDown(Buttons.A)) 
    #endif 

    then anything underneath this code will run exactly the same for xbox and pc 
  • 2/21/2010 1:36 AM In reply to

    Re: Converting Keyboard to Xbox Controller?

    Jason Guthrie:
    I think the best way is to use #if(XBOX360)  etc statements


    I would have to disagree... what if you wanted players to be able to use their Xbox controllers on the PC? Also remember that the keyboard still works on the Xbox (admittedly it's not common but it does work perfectly).

    Generic input is tricky - particularly if you want to use the thumbsticks on the xbox version as well as provide a mouse / keyboard alternative. I ended up creating a massive enum that contained values for all of the Keys enum, all of the mouse buttons and 4 x all of the gamepad buttons. I then had a IsButtonDown(GenericButton btn) method that determines which keyboard, gamepad or mouse button was requested and checks the correct input states based on that.

    Another layer of abstraction is provided by a IsButtonDownMapped(int btnId). The idea here is that the input system stores a map of int -> GenericButton[]. You will have a PlayerInput enum that has values like Left, Right, Jump, Duck etc. Using this system, each of the PlayerInput values can be bound to any number of configurable generic buttons. To support multiple players at once, I have a little method like this:

    int MapBtn(PlayerInput btn, int playerIndex)
    {
      return 100 * playerIndex + (int)btn;
    }

    then all of my input calls look like this:

    if (Input.IsButtonDownMapped(MapBtn(PlayerInput.Jump, playerId))
    {
    ...
    }

    The benefit is that the input is configurable at runtime, keys are handled in exactly the same way as mouse buttons and any differing input code paths for PC vs XBOX are restricted to one place - at startup. I wouldn't say it's the best possible solution to the gamepad vs keyboard conundrum, but it works well for me.
  • 2/22/2010 12:28 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    That helps but i still don't understand how to get that to work with the thumbsticks I'll input what i have now but i know its wrong

     

     

    Rectangle

     

    blackrec;

     

     

    private int Paddle1y;

     

     

    private int Paddle2y;

     

     

    private int Ballx;

     

     

    private int Bally;

     

     

    private int BallSpeedx;

     

     

    private int BallSpeedy;

     

     

    private Random random;

     

     

    private int BlueScore = 0;

     

     

    private int OrangeScore = 0;

     

     

    private GamePadState gpState;

     

     

    private ButtonState RightThumbStickUp;

     

     

    private Boolean RightThumbStickDown;

     

     

    private MouseState mouse;

     

     

    private int mousex;

     

     

    private int mousey;

     

     

    Rectangle Redrec;

     

     

    Rectangle Paddle2;

     

     

    Rectangle Paddle1;

     

     

    Texture2D mytexture;

     

     

    Rectangle Ball;

     

     

    Rectangle Goals;

     

     

    Rectangle PlayAgain;

     

     

    Rectangle cursor;

     

     

    SpriteFont SpriteFont1;

     

     

    Vector2 OrangePos;

     

     

    Vector2 BluePos;

     

     

    Vector2 PlayAgainBox;

     

     

    String OrangeString;

     

     

    String BlueString;

     

     

    String PlayAgainString;

     

     

    const int xCoord = 75;

     

     

    protected override void Initialize()

     

    {

     

    GamePadState gpState = GamePad.GetState(PlayerIndex.One);

     

    RightThumbStickUp = gpState.IsThumbStickDown(ThumbStick.Right));

    RightThumbStickDown =

    GamePadState.(Buttons.Down);

     

     

     

     

  • 2/22/2010 3:40 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    Hey Zach, please use the Format Code Block with a maximum height (fourth last toolbar button in the post editor) when posting that much code, else the mods won't be happy ;)

    Yeah, my generic input solution does indeed fall down when you actually want to use the Thumbstick's analog functionality. If you are just using it for going Up/Down/Left/Right, there isn't a problem. Have a look at Microsoft.Xna.Framework.Input.Buttons enum. This actually has values for all four directions of both Thumbsticks. This means you can say

    if (gpState.IsButtonDown(Buttons.LeftThumbstickRight))
    {
      // Player is pushing right
    }

    So a simple version of my setup could be to designate the keyboard as controller Id 5 and have methods like this:

     
    // you should store an array of game pad states (one for each controller) 
    GamePadState[] gpState; 
     
    // also very useful is an array of the previous frame's states 
    GamePadState[] gpStateLast; 
     
    // same deal for keyboard 
    KeyboardState kbState; 
    KeybaordState kbStateLast; 
     
    // in initialise or constructor 
    public MyClassName() 
      gpState = new GamePadState[4]; 
      gpStateLast = new GamePadState[4]; 
     
    // call every frame to poll input devices 
    public void Update() 
      for (int i = 0; i < 4; i++) 
      { 
        gpStateLast[i] = gpState[i] 
        gpState[i] = GamePad.GetState((PlayerIndex)i, GamePadDeadZone.Circular); 
      } 
     
      kbStateLast = kbState; 
      kbState = Keyboard.GetState(); 
     
     
    // Movement methods 
    public bool IsButtonDownLeft(int playerId) 
      if (playerId > 4) 
      { 
        //Keboard! 
        return kbState.IsKeyDown(Keys.Left); 
      } 
      else 
      { 
        // Gamepad 
        return gpState[playerId].IsButtonDown(Buttons.LeftThumbstickLeft); 
      } 
     
    // And the reason we have the "Last" states... 
    public bool IsButtonJustDownLeft(int playerId) 
      if (playerId > 4) 
      { 
        //Keboard! 
        return kbState.IsKeyDown(Keys.Left) &&  
               !kbStateLast.IsKeyDown(Keys.Left); 
      } 
      else 
      { 
        // Gamepad 
        return gpState[playerId].IsButtonDown(Buttons.LeftThumbstickLeft) && 
               !gpStateLast[playerId].IsButtonDown(Buttons.LeftThumbstickLeft); 
      } 

    If you don't like the idea of writing all those methods for every different possible input value, you might prefer to use a dictionary of Buttons -> Keys to define the gamepad -> keyboard equivalents... something like this:


     
    Dictionary<Buttons, Keys> keyMappings; 
      
    // in initialise or constructor 
    public MyClassName() 
      gpState = new GamePadState[4]; 
      gpStateLast = new GamePadState[4]; 
     
      keyMappings = new Dictionary<Buttons, Keys>(); 
      keyMappings.Add(Buttons.LeftThumbstickLeft, Keys.Left); 
      keyMappings.Add(Buttons.LeftThumbstickUp, Keys.Up); 
      // etc etc 
     
      
    // Movement methods  
    public bool IsButtonDown(int playerId, Buttons btn)  
    {  
      if (playerId > 4)  
      {  
        //Keboard!  
        // probably want better error handling here 
        Keys k = keyMappings[btn]; 
        return kbState.IsKeyDown(k);  
      }  
      else  
      {  
        // Gamepad  
        return gpState[playerId].IsButtonDown(btn);  
      }  
    }  

    If you want to use the dictionary method for key mappings, you will need to also look into using IEqualityComparer<T> to avoid garbage. See Nick's blog here for more info.
  • 3/1/2010 12:46 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    Thanks for the Help Roonda and everyone else I'm gonna change it as soon as i get home today
  • 3/1/2010 2:17 PM In reply to

    Re: Converting Keyboard to Xbox Controller?

    Here is what I did that may help you, but its a little long and drawn out.   I just made a controllerManager class that would give me access to bools that I made.  So I have public bool UpJustPressed() and public bool UpPressed(player index) the first being a single hit check and the second being a check to see if the button is held.
    then the second method looks like this (this is rough code and may not work directly)

    public bool UpPressed(PlayerIndex index)
    {
    if(keyboardState.isKeyDown(Key.Up) || gamepadState(index).Dpad.Down == buttonState.pressed || gamePadState(index).thumbSticks.left > 0.2f)
    return true;
    else
    return false;
    }

    Then for the UpJustPressed use

    public bool UpJustPressed(PlayerIndex index)
    {
    if((keyboardState.isKeyDown(Keys.Up) && perviousKeyboardState.isKeyUp(Keys.Up))|| 
       gamepadState(index).dpad.down == buttonstate.pressed && previousGamepadState(index).dpad.down != buttonstate.pressed
    return true;
    else return false;
    }

    For the keyboard though I just used another method that helped and this can be plugged into the top code to save time.

            /// <summary> 
            /// Check to see if a key was just pressed (down now but was up before) 
            /// </summary> 
            /// <param name="key">key to check</param> 
            /// <returns>True if key was just pressed and false if not pressed or is held</returns> 
            public static bool KeyJustPressed(Keys key) 
            { 
                if (keystate.IsKeyDown(key) && previousKeyState.IsKeyUp(key)) 
                    return true
                else 
                    return false
            } 
            /// <summary> 
            /// Check to see if a key is held down 
            /// </summary> 
            /// <param name="key">Key to check</param> 
            /// <returns>True while held down</returns> 
            public static bool KeyHeldDown(Keys key) 
            { 
                if (keystate.IsKeyDown(key)) 
                    return true
                else return false
            } 
     

Page 1 of 1 (12 posts) Previous Discussion Next Discussion