Keyboard Input similar to Gamepad with Input Systems

using UnityEngine;
using UnityEngine.InputSystem;

public class Movement : MonoBehaviour
{
    public Rigidbody rb;
    public float speed;

    void FixedUpdate()
    {
        var gamepad = Gamepad.current;
        var keyboard = Keyboard.current;
        if (gamepad == null)
            return;

        Vector2 move = gamepad.leftStick.ReadValue();
        rb.AddForce(-move.y * speed * Time.deltaTime, 0, move.x * speed * Time.deltaTime);
    }
}

I did a simple thing to get a nice force done when using the left stick on a controller. I want to know how to do this exact thing with a keyboard? How do I get vector 2 from WASD? I could add a force if a keyboard W, A, S, or D is pressed but that’s a lot of code, maybe it can be done easily?

Very easily… just start with a Vector2 variable set to Vector2.zero, then check each key and set the X and Y coordinates to either -1 or +1.

Finally to avoid going faster on diagonals, call .Normalize() on the Vector2 before you use it.

This is extremely common input code. Alternately there may be a way to do it through the Unity Keyboard stuff directly but I haven’t used that module yet.

1 Like

Thanks! It worked. :smile:

I have a new problem, the keyboard controls don’t work when the controller is disconnected, but if the controller is connected, both work. How do I fix this?

Excellent!

I would take this approach: once you have gathered the gamepad and the keyboard into separate Vector2 variables, just add them together into yet another Vector2 variable, then use that final Vector2 to decide how to move.

Vector2 FinalMove = KeyboardMove + GamepadMove;

Keeping them separate until the very end also lets you do other things to them if you want to adjust the inputs separately from keyboard vs gamepad, such as add filtering or smoothing.

1 Like