If you've noticed, inputs of 1.0 right and 1.0 forward will actually sum to a total of 2.0 units of speed. This means it is possible to move faster diagonally than it is to move in purely forward, backward, left, or right directions. What we really should do is clamp off any input value that results in speed in excess of 1.0 units while maintaining the direction of input indicated. We can do this by storing the previous input values, and overriding the ::Tick()
function.
AWarrior::SetupPlayerInputComponent( UInputComponent* Input )
function as follows:void AWarrior::SetupPlayerInputComponent( UInputComponent* Input ) { Input->BindAxis( "Forward", this, &AWarrior::Forward ); Input->BindAxis( "Back", this, &AWarrior::Back ); Input->BindAxis( "Right", this, &AWarrior::Right ); Input->BindAxis( "Left", this, &AWarrior::Left ); }
::Forward
, ::Back
, ::Right
and ::Left
functions as follows:void AWarrior::Forward( float amount ) { // We use a += of the amount added so that // when the other function modifying .Y // (::Back()) affects lastInput, it won't // overwrite with 0's lastInput.Y += amount; } void AWarrior::Back( float amount ) { lastInput.Y += -amount; } void AWarrior::Right( float amount ) { lastInput.X += amount; } void AWarrior::Left( float amount ) { lastInput.X += -amount; }
AWarrior::Tick()
function, modify the input values after normalizing any oversize in the input vector:void AWarrior::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); if( Controller ) { float len = lastInput.Size(); if( len > 1.f ) lastInput /= len; AddMovementInput( GetActorForwardVector(), lastInput.Y ); AddMovementInput(GetActorRightVector(), lastInput.X); // Zero off last input values lastInput = FVector2D( 0.f, 0.f ); } }
18.119.255.44