Search code examples
c#inputmonogamejoystick

Monogame, C# - Using multiple input types for multiplayer game


I'm making a local multiplayer game. I need to be able to use both keyboard input (most likely only for player one) and other joystick controllers for the rest of the players. I cannot use PlayerIndex as most other games do as it is made for controllers and doesn't include keyboard input. What would be the best way to go about this?


Solution

  • It's not entirely clear whether you want to support an OPTION for selecting an input type, or if you actually want to use several input types simultaneously. However since you're mentioning Multiplayer, I'm guessing you're simply looking for a solution to allow the player to select between keyboard and controller input.

    This is really quite simple:

    interface IGameInput
    {
        float GetXMovement();
        float GetYMovement();
    }
    
    class KeyboardInput : IGameInput
    {
        public float GetXMovement()
        {
            var state = Keyboard.GetState();
            var leftDown = state.IsKeyDown(Keys.A);
            var rightDown = state.IsKeyDown(Keys.D);
            float finalValue = 0;
            if (leftDown)
                 finalValue -= 1;
            if (rightDown )
                 finalValue += 1;
            return finalValue;
        }
        public float GetYMovement()
        {
            // Same as X, just check for W and S instead.
        }
    }
    
    class ControllerInput : IGameInput
    {
        public float GetXMovement()
        {
            var state = Gamepad.GetState(0); // or whatever the syntax is, I forgot.
            var xMovement = state.LeftThumb.X;
            return xMovement;
        }
        public float GetYMovement()
        {
            var state = Gamepad.GetState(0); // same as above
            var yMovement = state.LeftThumb.Y;
            return yMovement;
        }
    }
    
    // other class
    var x = this.input.GetXMovement() * this.MovementSpeed;
    var y = this.input.GetYMovement() * this.MovementSpeed;
    this.Position = this.Position + new Vector2(x, y);
    

    Very basic concept. Notice that this means that on a keyboard, you will always be moving 100% or 0% of movement speed, while when using a controller, if you only move the thumb 50% to the left, it will only move with 50% speed to the left.

    To summarize: Create an interface that delegates the requests of movement controls, and replace the implementation according to whether the user uses keyboard or Gamepad controller.