words on sand

from shri at drone-ah.com

25 Jan 2015

[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.

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/* 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

1
2
3
4
5
6
7
8
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:

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

And implement the rest of the methods

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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"));
}