How to get key used for input?

Currently, I’m searching for the c++ equivalent of getting the key used for an input, like in this blueprint:

95048-78898106196588b9c48b6e87c82e0cd3.png

This sort of behavior will require a bit more work on the C++ end. There’s not a universal event that’s emitted when a key is pressed.

In C++ you have a couple of options. You could monitor key presses within your player controllers Tick() function, checking WasInputKeyJustPressed(). You could also create a new InputComponent, which would allow you to better monitor input. Other than that, for keys you expect to be using, BindAction() will be your friend.

What are you trying to do that binding an input within Settings > Input isn’t handling?

I’m checking for how long the key was held down. So, holding down the interact key for one second triggers an event. I have it working flawlessly in BP, but I need to get the key so I check how long it’s held for in c++ (The keybindings are changeable so I can’t just hard code it in).

You’ll use GetKeysForAction on PlayerInput to figure out what key is currently associated with the action you’re looking for. Find the key and maintain a timer to replicate the behavior in C++.

How’s the adventure going? Get things worked out?

This behavior can be achieved by just adding an “FKey” parameter to the bound method.

Create an Action input mapping on the ProjectSettings, then add all the key binds you need (AnyKey if you want all keys). Then use it like this on your code:

MyPlayerController.h

virtual void SetupInputComponent() override;

void TryAction(FKey key);

MyPlayerController.cpp

void AMyPlayerController::SetupInputComponent() {
	Super::SetupInputComponent();
	InputComponent->BindAction("MyAction", EInputEvent::IE_Pressed, this, &AMyPlayerController::TryAction);
}

void AMyPlayerController::TryMorph(FKey key)
{
	FName keyName = key.GetFName();
}
1 Like

This was exactly what I was hoping for. Also FKey has a function IsGamepadKey(), which is the reason I needed it - to alter how the character works depending on whether it’s keyboard or gamepad (input is hold vs toggle).

You can use UGameplayStatics::GetPlayerController(GetWorld(), 0)->GetInputKeyTimeDown(FKey("AnyKey"))

float howLongTheKeyIsPressed = UGameplayStatics::GetPlayerController(GetWorld(), 0)->GetInputKeyTimeDown(FKey("W"));

     // This is for the jump function.
	if (bPressedJump)
	{
		
		//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("How long was the key pressed: %f"),  howLongTheKeyIsPressed ));
               // If longer than few seconds then do this, else that
		if (howLongTheKeyIsPressed*10.f > 5.f)
		{
			return;
		}
		else
		{
			// do
		}

	}
2 Likes