Reacting to user input was always a little naff in Unreal Engine: define an input, then build a rather complex graph with booleans around it to see if a key is pressed or released, all of which using a section of the Project Settings to map the actual input sources and axis. It felt a little out of place, but it was simple enough to understand. With Unreal Engine 5.1, EPIC have introduced an overhauled system that makes it a little easier for us to query inputs and react to them by way of Enhanced User Inputs.
Now we can create a new Input Action class and decide what it needs to query (say a boolean on/off value or axis mapping), then we add it to a Mapping Context. The latter will trigger an event we can react to in our event graph, complete with access to all kinds of data we didn’t have before.
Let me show you an example of adding a Sprint action to a Third Person project. We already have an Input folder in the project, in which I’ll create a new action called IA_Sprint in the Actions folder.
It’ll be a boolean, and that’s really all I have to setup in this file. The description is optional.
I need to add this new action to the Input Mapping Context, which is provided one folder up from the actions, and it’s called IMC_Default. We can create our own too, but this one is already mapped in the player character (we’ll see how it gets called in a moment).
Once my action is added with the little plus icon, I can set the inputs for my action, just like I used to under Project Settings in UE4 projects. Those options are still available in case you don’t want to deal with all this newfangled malarkey right now. I’ll use my left SHIFT key for sprinting, but I can expand this later with controller mappings if I want. Examine how they’ve setup the Jump, Move and Look actions to learn more about how axis mappings work.
To react to our input, we go back to our Player Character file, where I an now use an event called EnhancedInputAction IA_Sprint. From here I can react to what happened when my key was pressed (triggered) or released (completed). I’m using it to set a different walk speed for my character.
What I like about this system is that we don’t have to create additional variables to track states for things like this (think crouching, swimming, jumping). While that’s a nice bonus, it gets way better when it comes to making the player press a button for two seconds: we have access to the Elapsed Seconds in the advanced tab. Perhaps I want the player to hold down SHIFT before my character starts sprinting, in which case I can do something like this:
I can easily test if stamina runs, or even display an animation that shows depletion. Long presses have never been handled this conveniently.
In case we ever need to setup out own custom Mapping Context, it’s done in Begin Play from the Player Controller.