[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();

protected:
	/** 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
	DisableSprint();
}

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"));
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.