It’s fairly common that we want to use the Gameplay Ability System to control a character’s speed. For example, sprinting, sneaking or crouching related abilities might all affect how fast the character can move.
The CharacterMovementComponent has its own speed settings, but it’s quite easy to replace it in C++ to read the maximum speed value from an AttributeSet instead.
Using an AttributeSet as the Max Speed for CharacterMovementComponent
All we need to do is create a custom CharacterMovementComponent
subclass, and override GetMaxSpeed
:
float UMyCharacterMovementComponent::GetMaxSpeed() const
{
if(MovementMode == MOVE_Walking)
{
if(const auto* ASC = UAbilitySystemGlobals::GetAbilitySystemComponentFromActor(GetOwner()))
{
return ASC->GetNumericAttribute(UMyAttributeSet::GetMaxSpeedAttribute());
}
}
return Super::GetMaxSpeed();
}
In this example, as long as the movement mode is Walking
, the speed is read from the Max Speed attribute.