enhanced input

Using the Enhanced Input Plugin to read and interpret user input

Windows
MacOS
Linux

For projects that require more advanced input features, like complex input handling or runtime control remapping, the experimental Enhanced Input Plugin gives developers an easy upgrade path and backward compatibility with the engine's default input system. This plugin implements features like dead zones, chorded actions, contextual input and prioritization, and the ability to extend your own filtering and processing of raw input data in an Asset-based environment.

Getting Started

To configure your project to use Enhanced Input, enable the Enhanced Input Plugin. You can do this by opening the Edit dropdown menu in the editor and selecting Plugins. Under the Input section of the Plugin List, find and enable the Enhanced Input Plugin, then restart the editor.

EnhancedInputPlugin.png

The plugin will become active after you restart the editor.

Once the editor has restarted, you can set your project to use Enhanced Input Plugin classes instead of the default UE4 input handlers. Go to the Edit dropdown menu and choose Project Settings. From there, locate the Input section (under the Engine heading) and find the Default Classes settings. These will initially contain the standard PlayerInput and InputComponent classes.

EnhancedInputDefaultClasses.png

To use Enhanced Input, change these settings to EnhancedPlayerInput and EnhancedInputComponent, respectively.

EnhancedInputDefaultClasses2.png

Core Concepts

The Enhanced Input system has four main concepts:

  • Input Actions are the communication link between the Enhanced Input system and your project's code. An Input Action can be anything that an interactive character might do, like jumping or opening a door, but could also be used to indicate user input states, like holding a button that changes walking movement to running. Input Actions are separate from raw input; an Input Action is not concerned with the specific input that triggered it, but does know its current state and can report an input value on up to three independent floating-point axes. As an example, a "pick up item" Action might only need an on/off state, indicating whether or not the user is trying to pick something up, while a "walk" Action might require two axes to describe the direction and speed at which the user is trying to walk.

  • Input Mapping Contexts map user inputs to Actions and can be dynamically added, removed, or prioritized for each user. You can apply one or more Contexts to a local player through its Enhanced Input Local Player Subsystem, and prioritize them to resolve collisions between multiple actions trying to consume the same input. A common example of this might be a single button that can open doors while the character is walking around in the world, or select an item while looking through the character's backpack. Whenever the character opens the backpack, you could add a "select item" Input Mapping Context that out-prioritizes the "open door" context, and then remove the "select item" context when the character closes the backpack. This would ensure that the user's inputs will be interpreted correctly based on the character's situation, and prevent the need to program code at the input-handling level with awareness of the door and backpack systems.

  • Modifiers adjust the value of raw input coming from the user's devices. An Input Mapping Context can have any number of modifiers associated with each raw input for an Input Action. Common Modifiers including dead zones, input smoothing over multiple frames, conversion of input vectors from local to world space, and several others are included in the plugin; developers can also create their own Modifiers.

  • Triggers use post-Modifier input values, or the output magnitudes of other Input Actions, to determine whether or not an Input Action should activate. Any Input Action within an Input Mapping Context can have one or more Triggers for each input. For example, taking a photograph might require that the user holds down the Left Mouse Button for a quarter of a second while a separate Input Action for aiming the camera is active.

By combining these concepts, developers can quickly set up input systems ranging from simple to complex, and adjust these systems without having to change project code.

Input Actions

Input Actions are the connection between the system and your project's code. You can create an Input Action by right-clicking in the Context Browser, expanding the Input option, and choosing Input Action. To trigger an Input Action, you must include it in an Input Mapping Context, and add that Input Mapping Context to the local player's Enhanced Input Local Player Subsystem.

EnhancedInput_CreateAsset.png

To make your Pawn class respond to a triggered Input Action, you must bind it to the appropriate type of Trigger Event in SetupPlayerInputComponent. The following sample code overrides SetupPlayerInputComponent to bind two Input Actions, MyInputAction and MyOtherInputAction, to handler functions:

// Make sure that we are using a UEnhancedInputComponent; if not, the project is not configured correctly.
if (UEnhancedInputComponent* PlayerEnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent))
{
    // There are ways to bind a UInputAction* to a handler function and multiple types of ETriggerEvent that may be of interest.

    // This calls the handler function on the tick when MyInputAction starts, such as when pressing an action button.
    if (MyInputAction)
    {
        PlayerEnhancedInputComponent->BindAction(MyInputAction, ETriggerEvent::Started, this, &AMyPawn::MyInputHandlerFunction);
    }

    // This calls the handler function (a UFUNCTION) by name on every tick while the input conditions are met, such as when holding a movement key down.
    if (MyOtherInputAction)
    {
        PlayerEnhancedInputComponent->BindAction(MyOtherInputAction, ETriggerEvent::Triggered, this, TEXT("MyOtherInputHandlerFunction"));
    }
}

Binding Input Actions with the Enhanced Input Plugin replaces the built-in input system's Action and Axis bindings; if you are using the Enhanced Input Plugin, you should only bind Input Actions.

When binding Input Actions, you can choose between four different handler function signatures, as follows:

Return Type

Parameters

Usage Notes

void

()

Suitable for simple cases where you don't need any extra information from the Enhanced Input system

void

(const FInputActionValue& ActionValue)

Provides access to the current value of the Input Action

void

(const FInputActionInstance& ActionInstance)

Signature used when dynamically binding to a UFunction by its name; parameters are optional

The primary purpose of this type of binding is to expose Input Actions to Blueprint Scripting. Since the Enhanced Input Plugin does this automatically, developers should rarely need to use this binding method.

void

(FInputActionValue ActionValue, float ElapsedTime, float TriggeredTime)

Input Actions have built-in events that expose them to Blueprints Scripting; C++ developers do not have to create pass-through functions to give Blueprint Scripting developers access to Input Action events.

A typical handler function might take the following form:

void AMyPawn::MyFirstAction(const FInputActionValue& Value)
{
    // Debug log output to confirm that the handler function is running.
    UE_LOG(LogTemp, Warning, TEXT("%s called with Input Action Value %s (magnitude %f)"), TEXT(__FUNCTION__), *Value.ToString(), Value.GetMagnitude());
    // Use the GetType() function to determine Value's type, and the [] operator with an index between 0 and 2 to access its data.
}

For most use cases, using the void (const FInputActionValue&) signature is recommended.

Binding Input Actions to handler functions enables the Pawn to respond to them depending on the specific way that they are triggered. The most common trigger types are likely to be Started for actions that happen once, immediately upon pressing a button, and Triggered for continuous actions that happen every frame while holding an input, but you can view the complete list at the API reference page for ETriggerEventETriggerEvent.

Input Mapping Contexts

Input Mapping Contexts describe the rules for triggering one or more Input Actions. Its basic structure is a hierarchy with a list of Input Actions at the top level. Under the Input Action level is a list of user inputs that can trigger each Input Action, such as keys, buttons, and movement axes. The bottom level contains a list of Input Triggers and Input Modifiers for each user input, which you can use to determine how an input's raw value is filtered or processed, and what restrictions it must meet in order to drive the Input Action at the top of its hierarchy. Any input can have multiple Input Modifiers and Input Triggers. These will evaluate in the order in which they appear in the list you create; this is particularly important for Input Modifiers, which use the output of each step as the input for the next.

To create an Input Mapping Context, right-click the Context Browser, expand the Input option, and choose Input Mapping Context.

EnhancedInput_CreateAsset.png

Populate your Input Mapping Context with all of the relevant Input Actions. For a simple project, you may be able to put all of your Input Actions into a single Input Mapping Context. More complex projects may work best with multiple Input Mapping Contexts, since a local player can have more than one active Input Mapping Context at a time. As an example, a character who can swim, walk, and drive vehicles might have multiple Input Mapping Contexts; one for common actions that are always available and always mapped to the same user inputs, and one more for each individual mode of travel. Developers could then place the vehicle-related Input Actions into a separate Input Mapping Context, which they can then add to the local player upon entering a vehicle, and remove from the local player upon exiting. Doing this helps to reduce bugs by ensuring that inappropriate Input Actions cannot run (and don't waste CPU cycles), and by avoiding input collisions when a user input is used for different Input Actions by mutually-exclusive Input Mapping Contexts. See the sections on Modifiers and Triggers for more details.

InputMappingContext_Hierarchy.png

This Input Mapping Context shows an Input Action for running, which can be activated by multiple inputs, including a gamepad's left thumbstick deflection, combining both axes into a single input. That input's raw value will go through a "dead zone" Input Modifier, and the resulting value will be sent to the "hold" Input Trigger to drive the "RunAction" Input Action.

InputMappingContext_Key.png

There are a large number of input bindings available in the dropdown list. To select your input binding more quickly, press the small button to the left of the dropdown, and then press the key or button you want to bind.

InputMappingContext.png

This simple Input Mapping Context supports Input Actions for running and jumping.

Once you have populated an Input Mapping Context, you can add it to the Local Player associated with the Pawn's Player Controller. Do this by overriding the PawnClientRestart function and adding a code block like this:

// Make sure that we have a valid PlayerController.
if (APlayerController* PC = Cast<APlayerController>(GetController()))
{
    // Get the Enhanced Input Local Player Subsystem from the Local Player related to our Player Controller.
    if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PC->GetLocalPlayer()))
    {
        // PawnClientRestart can run more than once in an Actor's lifetime, so start by clearing out any leftover mappings.
        Subsystem->ClearAllMappings();

        // Add each mapping context, along with their priority values. Higher values outprioritize lower values.
        Subsystem->AddMappingContext(MyInputMappingContext, MyInt32Priority);
    }
}

With your Input Mapping Contexts added, your Pawn is able to respond to any Input Action events you bound in SetupPlayerInputComponent, or that Blueprint Scripting users have set up. If events occur during gameplay that warrant changing the set of available Input Mapping Contexts, you can use ClearAllMappings, AddMappingContext, and RemoveMappingContext to update the set of available commands dynamically. Check the IEnhancedInputSubsystemInterfaceIEnhancedInputSubsystemInterface API reference page for more information.

Input Modifiers

Input Modifiers are pre-processors that alter the raw input values that UE4 receives before sending them on to Input Triggers. The Enhanced Input Plugin ships with a variety of Input Modifiers to perform tasks like changing the order of axes, implementing "dead zones", converting axial input to world space, and several others. Each input associated with an Input Action within an Input Mapping Context will go through a user-defined series of Input Modifiers before proceeding to the Input Trigger (or Input Triggers) for that input. Input Modifiers are applied in the order they are listed, and the output value from each Input Modifier becomes the input value for the next.

To see the complete list of Input Modifiers included with the Enhanced Input Plugin, check the UInputModifierUInputModifier API reference page. If your project requires an Input Modifier that doesn't already exist, you can create your own UInputModifier class.

Directional Input

A good example of Input Modifier usage is two-dimensional directional input using a single Input Action. With a mouse or a gamepad's analog stick, reading two-dimensional movement is a simple matter of creating an Input Action that supports at least two axes and adding the appropriate input to the Input Mapping Context. However, if you would also like to support input from one-dimensional sources, such as a keyboard's directional arrows or the popular "WASD" configuration, you can do so by applying the correct Input Modifiers. Specifically, "Negate" to make some keys register as negative, and "Swizzle Input Axis Values" to make some keys register as Y-Axis instead of the default X-Axis. To do this, configure your inputs as follows:

Letter Key

Arrow Key

Desired Input Interpretation

Required Input Modifiers

W

Up

Positive Y-Axis

Swizzle Input Axis Values (YXZ or ZXY)

A

Left

Negative X-Axis

Negate

S

Down

Negative Y-Axis

Negate

Swizzle Input Axis Values (YXZ or ZXY)

D

Right

Positive X-Axis

(none)

InterpretingWASD.png

This interpretation of the directional arrows or "WASD" keys enables one-dimensional inputs to map to a two-dimensional Input Action.

Since each key reports a positive, one-dimensional value, this value will always occupy the X-axis and will have a value of either 0.0 or 1.0 on any given tick. By negating the value for left and down inputs, and switching the axis order so that the input's X-axis value moves to the Y-axis for up and down inputs, you can use Input Modifiers to interpret a set of one-dimensional inputs as a single two-dimensional input value.

Input Triggers

Input Triggers determine whether or not a user input, after passing through an optional list of Input Modifiers, should activate the corresponding Input Action within its Input Mapping Context. Most Input Triggers analyze the input itself, checking for minimum actuation values and validating patterns like short taps, prolonged holds, or the typical "press" or "release" events. The one exception to this rule is the "Chorded Action" Input Trigger, which requires another Input Action to be triggered. By default, any user activity on an input will trigger on every tick.

To see the complete list of Input Triggers included with the Enhanced Input Plugin, check the UInputTriggerUInputTrigger API reference page. If you need an Input Trigger that the Enhanced Input Plugin does not provide, you can create your own UInputTrigger class.

언리얼 엔진 문서의 미래를 함께 만들어주세요! 더 나은 서비스를 제공할 수 있도록 문서 사용에 대한 피드백을 주세요.
설문조사에 참여해 주세요
건너뛰기