Axis Mappings – normalized input

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.

Getting ready

Open a project, and set up a Character derivative class (let's call ours Warrior).

How to do it…

  1. Override the 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 );
    }
  2. Write the corresponding ::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;
    }
  3. In the 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 );
      }
    }

How it works...

We normalize the input vector when it is over a magnitude of 1.0. This constricts the maximum input velocity to 1.0 units (rather than 2.0 units when full up and full right are pressed, for example).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.255.44