> For the complete documentation index, see [llms.txt](https://lifeexe-art.gitbook.io/unreal-engine-c-course/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lifeexe-art.gitbook.io/unreal-engine-c-course/voprosy-i-otvety/kak-rabotaet-kod-s-pereopredeleniem-getmaxspeed.md).

# Как работает код с переопределением GetMaxSpeed

{% hint style="info" %}
**Я не понимаю, как в вашей реализации получается, что мы переписываем геттер GetMaxSpeed(), который просто возвращает значение и при этом в игре меняется MaxWalkSpeed. Мы даже не вызываем этот геттер в своих классах. Я так подозреваю, что наш новый GetMaxSpeed() используется где-то в AddMovementInput(), но подтверждения я в референсах не нашёл. Не могли бы вы внести ясность?**
{% endhint %}

`AddMovementInput` устанавливает вектор направления в компоненте движения (если он существует):

```cpp
void APawn::AddMovementInput(FVector WorldDirection, float ScaleValue, bool bForce /*=false*/)
{
    UPawnMovementComponent* MovementComponent = GetMovementComponent();
    if (MovementComponent)
    {
        MovementComponent->AddInputVector(WorldDirection * ScaleValue, bForce);
    }
    else
    {
        Internal_AddMovementInput(WorldDirection * ScaleValue, bForce);
    }
}
```

Сам компонент отвечает за то, как положение персонажа будет изменяться в зависимости от разных параметров и условий.

Функция `GetMaxSpeed` используется во многиx функциях внутри компонента. Например, в `CalcVelocity` (код не полный, функция большая, понимать код не обязательно, это детали реализации):

```cpp
void UCharacterMovementComponent::CalcVelocity(float DeltaTime, float Friction, bool bFluid, float BrakingDeceleration)
{
   // Do not update velocity when using root motion or when SimulatedProxy and not simulating root motion - SimulatedProxy are repped their Velocity
   if (!HasValidData() || HasAnimRootMotion() || DeltaTime < MIN_TICK_TIME || (CharacterOwner && CharacterOwner->GetLocalRole() == ROLE_SimulatedProxy && !bWasSimulatingRootMotion))
   {
       return;
   }
 
   Friction = FMath::Max(0.f, Friction);
   const float MaxAccel = GetMaxAcceleration();
   float MaxSpeed = GetMaxSpeed();
	
   // Check if path following requested movement
   bool bZeroRequestedAcceleration = true;
   FVector RequestedAcceleration = FVector::ZeroVector;
   float RequestedSpeed = 0.0f;
   if (ApplyRequestedMove(DeltaTime, MaxAccel, MaxSpeed, Friction, BrakingDeceleration, RequestedAcceleration, RequestedSpeed))
   {
       bZeroRequestedAcceleration = false;
    }
...
}
```

Таким образом, переопределяя данную функцию, мы изменяем максимальную скорость персонажа.

Более того, сама функция имеет вид:

```cpp
float UCharacterMovementComponent::GetMaxSpeed() const
{
   switch(MovementMode)
   {
    case MOVE_Walking:
    case MOVE_NavWalking:
        return IsCrouching() ? MaxWalkSpeedCrouched : MaxWalkSpeed;
    case MOVE_Falling:
        return MaxWalkSpeed;
    case MOVE_Swimming:
        return MaxSwimSpeed;
    case MOVE_Flying:
        return MaxFlySpeed;
    case MOVE_Custom:
        return MaxCustomMovementSpeed;
    case MOVE_None:
    default:
        return 0.f;
    }
}
```

В нашем коде с переопределением скорость будет увеличиваться во всех случаях, но это уже зависит от дизайна игры.
