[UE4] Getting Sprint to work (C++)

Getting Shift to sprint in the Unreal Engine 4 is very easy. There are technically two ways of doing it.

  • Change the scale down to say 0.5 and then increase it to 1.0 for sprinting
  • Change the MaxWalkSpeed for walking and sprinting.

I prefer the second technique because it will keep the code simple enough and continue to function as expected with analog controllers.

Lets start by adding the input action bindings

Edit -> Project Settings -> Input -> Bindings and add an action for Sprint with Left Shift for the key.

All the code is in the Character class.

Within the header file, there are two blueprint variables for the WalkSpeed and SprintSpeed so they can be modified easily.

We also override the BeginPlay() Method. This is used to default to Walking.

Add the following to your character header file

	/** The speed at which the character will be walking */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Character)
	uint16 WalkSpeed;

	/** The speed at which the character will be sprinting*/
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Character)
	uint16 SprintSpeed;

	virtual void BeginPlay();

	/** Enables Sprinting for the character*/
	void EnableSprint();

	/** Disables Sprinting again */
	void DisableSprint();

Add the following to the constructor so we have defaults

AMyCharacter::AMyCharacter(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)

    // Other code
	// Set the default Defaults šŸ˜‰
	WalkSpeed = 250;
	SprintSpeed = 600;


Plug in the Sprint action to the methods by adding the following lines into theĀ SetupPlayerInputComponentĀ method:

	InputComponent->BindAction("Sprint", IE_Pressed, this, &AMyCharacter::EnableSprint);
	InputComponent->BindAction("Sprint", IE_Released, this, &AMyCharacter::DisableSprint);

And implement the rest of the methods

void AVSCharacter::BeginPlay()

    // Ensure the player starts with Walking

void AVSCharacter::EnableSprint()
	CharacterMovement->MaxWalkSpeed = SprintSpeed;
	GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Black, TEXT("Sprintin"));

void AVSCharacter::DisableSprint()
	CharacterMovement->MaxWalkSpeed = WalkSpeed;
	GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Black, TEXT("Walkin"));