TExcelTAD
Home › Unreal Engine 5 with C++ › Mini Project: Arena Duel

Mini Project: Arena Duel

Time to build a small but complete Unreal game: Arena Duel. A third-person hero fights one AI enemy in a walled arena. Both have health managed by the Gameplay Ability System. Both can melee. The hero also has one ability, Shockwave, which damages and knocks back anything nearby and then goes on a 5-second cooldown. Kill the Grunt and you win; die and you lose; either way the arena restarts after 3 seconds.

It uses most of the course: a module with Build.cs, the gameplay framework (GameMode, Character, AIController), reflection and TObjectPtr, Enhanced Input, a sweep trace, GAS (attribute set, damage effect, an ability with a cooldown tag), a Behavior Tree with a C++ task, timers and delegates.

Step What you build Lessons
1 project, module, tags Projects, Modules & Build.cs, Gameplay Tags
2 attribute set and the shared character base GAS: Attributes & Effects, Traces & Collision Channels
3 the player character with input Enhanced Input, PlayerController, Pawn, Character & HUD
4 the Shockwave ability GAS: Abilities
5 the enemy, its controller and Behavior Tree task AIController, Behavior Trees
6 the GameMode: win, lose, restart GameMode, GameState & PlayerState, Timers
7 editor steps: assets, Blueprints, the level
8 a runnable model of the combat rules

The game is single-player, so it skips replication. Every class still uses the patterns that keep the door open (server-authoritative damage through GAS, logic in the framework classes), and the closing section lists what multiplayer would need.

Step 1: Project, module and tags

Create a project from the Third Person template, C++, named Arena. Enable the Gameplay Abilities plugin (Edit → Plugins), restart, then edit the module rules:

csharp
// Source/Arena/Arena.Build.cs
using UnrealBuildTool;

public class Arena : ModuleRules
{
    public Arena(ReadOnlyTargetRules Target) : base(Target)
    {
        PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

        PublicDependencyModuleNames.AddRange(new string[]
        {
            "Core", "CoreUObject", "Engine", "InputCore", "EnhancedInput",
            "GameplayAbilities", "GameplayTags", "GameplayTasks"
        });

        PrivateDependencyModuleNames.AddRange(new string[] { "AIModule", "NavigationSystem" });
    }
}

GameplayAbilities is public because our public headers include AbilitySystemInterface.h.

cpp
// Source/Arena/ArenaTags.h
#pragma once

#include "NativeGameplayTags.h"

UE_DECLARE_GAMEPLAY_TAG_EXTERN(TAG_Data_Damage);          // SetByCaller key for GE_Damage
UE_DECLARE_GAMEPLAY_TAG_EXTERN(TAG_Cooldown_Shockwave);   // granted by GE_Shockwave_Cooldown
UE_DECLARE_GAMEPLAY_TAG_EXTERN(TAG_Status_Dead);
cpp
// Source/Arena/ArenaTags.cpp
#include "ArenaTags.h"

UE_DEFINE_GAMEPLAY_TAG(TAG_Data_Damage, "Data.Damage");
UE_DEFINE_GAMEPLAY_TAG(TAG_Cooldown_Shockwave, "Cooldown.Shockwave");
UE_DEFINE_GAMEPLAY_TAG(TAG_Status_Dead, "Status.Dead");

The template also generated a character and GameMode class. You can delete them (and their Blueprints) or keep them for reference; the classes below replace them.

Step 2: Attributes and the shared character base

The attribute set from the GAS lesson, trimmed to what the duel needs. Damage arrives through the IncomingDamage meta attribute and is turned into a Health change, and a death notification, in one place.

cpp
// Source/Arena/ArenaAttributeSet.h
#pragma once

#include "CoreMinimal.h"
#include "AttributeSet.h"
#include "AbilitySystemComponent.h"
#include "ArenaAttributeSet.generated.h"

UCLASS()
class ARENA_API UArenaAttributeSet : public UAttributeSet
{
    GENERATED_BODY()

public:
    UPROPERTY(BlueprintReadOnly, Category = "Attributes")
    FGameplayAttributeData Health;
    GAMEPLAYATTRIBUTE_PROPERTY_GETTER(UArenaAttributeSet, Health);
    GAMEPLAYATTRIBUTE_VALUE_GETTER(Health);
    GAMEPLAYATTRIBUTE_VALUE_SETTER(Health);
    GAMEPLAYATTRIBUTE_VALUE_INITTER(Health);

    UPROPERTY(BlueprintReadOnly, Category = "Attributes")
    FGameplayAttributeData MaxHealth;
    GAMEPLAYATTRIBUTE_PROPERTY_GETTER(UArenaAttributeSet, MaxHealth);
    GAMEPLAYATTRIBUTE_VALUE_GETTER(MaxHealth);
    GAMEPLAYATTRIBUTE_VALUE_SETTER(MaxHealth);
    GAMEPLAYATTRIBUTE_VALUE_INITTER(MaxHealth);

    UPROPERTY(BlueprintReadOnly, Category = "Attributes")
    FGameplayAttributeData IncomingDamage;
    GAMEPLAYATTRIBUTE_PROPERTY_GETTER(UArenaAttributeSet, IncomingDamage);
    GAMEPLAYATTRIBUTE_VALUE_GETTER(IncomingDamage);
    GAMEPLAYATTRIBUTE_VALUE_SETTER(IncomingDamage);

    virtual void PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue) override;
    virtual void PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data) override;
};
cpp
// Source/Arena/ArenaAttributeSet.cpp
#include "ArenaAttributeSet.h"
#include "ArenaCharacterBase.h"
#include "GameplayEffectExtension.h"

void UArenaAttributeSet::PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue)
{
    Super::PreAttributeChange(Attribute, NewValue);
    if (Attribute == GetHealthAttribute())
    {
        NewValue = FMath::Clamp(NewValue, 0.f, GetMaxHealth());
    }
}

void UArenaAttributeSet::PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data)
{
    Super::PostGameplayEffectExecute(Data);
    if (Data.EvaluatedData.Attribute != GetIncomingDamageAttribute()) return;

    const float Damage = GetIncomingDamage();
    SetIncomingDamage(0.f);
    if (Damage <= 0.f || GetHealth() <= 0.f) return;           // no healing through damage; no hitting the dead

    SetHealth(FMath::Clamp(GetHealth() - Damage, 0.f, GetMaxHealth()));
    if (AArenaCharacterBase* Owner = Cast<AArenaCharacterBase>(GetOwningActor()))
    {
        Owner->HandleHealthChanged(GetHealth(), GetMaxHealth());
        if (GetHealth() <= 0.f)
        {
            Owner->HandleDeath();
        }
    }
}

The base class is shared by the hero and the Grunt: the ability system, starting health, a melee attack (a sphere sweep in front of the character), damage through GE_Damage, and death.

cpp
// Source/Arena/ArenaCharacterBase.h
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "AbilitySystemInterface.h"
#include "ArenaCharacterBase.generated.h"

class UAbilitySystemComponent;
class UArenaAttributeSet;
class UGameplayAbility;
class UGameplayEffect;
class UAnimMontage;

DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnArenaHealthChanged, float, Health, float, MaxHealth);

UCLASS(Abstract)
class ARENA_API AArenaCharacterBase : public ACharacter, public IAbilitySystemInterface
{
    GENERATED_BODY()

public:
    AArenaCharacterBase();

    virtual UAbilitySystemComponent* GetAbilitySystemComponent() const override { return AbilitySystem; }

    /** Melee in front of the character. Returns false if on cooldown or dead. */
    UFUNCTION(BlueprintCallable, Category = "Combat")
    bool TryMeleeAttack();

    UFUNCTION(BlueprintPure, Category = "Combat")
    bool IsAttacking() const;

    UFUNCTION(BlueprintPure, Category = "Combat")
    bool IsDead() const { return bIsDead; }

    /** Applies GE_Damage with a SetByCaller magnitude to any actor with an ability system. */
    void ApplyDamageTo(AActor* Target, float Amount);

    void HandleHealthChanged(float Health, float MaxHealth);
    void HandleDeath();

    UPROPERTY(BlueprintAssignable, Category = "Combat")
    FOnArenaHealthChanged OnHealthChanged;     // the health bar widget binds here

protected:
    virtual void BeginPlay() override;

    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Abilities")
    TObjectPtr<UAbilitySystemComponent> AbilitySystem;

    UPROPERTY()
    TObjectPtr<UArenaAttributeSet> Attributes;

    UPROPERTY(EditDefaultsOnly, Category = "Abilities")
    TArray<TSubclassOf<UGameplayAbility>> StartupAbilities;

    UPROPERTY(EditDefaultsOnly, Category = "Combat")
    TSubclassOf<UGameplayEffect> DamageEffectClass;          // GE_Damage

    UPROPERTY(EditDefaultsOnly, Category = "Combat", meta = (ClampMin = "1"))
    float StartingHealth = 100.f;

    UPROPERTY(EditDefaultsOnly, Category = "Combat")
    float MeleeDamage = 20.f;

    UPROPERTY(EditDefaultsOnly, Category = "Combat", meta = (Units = "cm"))
    float MeleeRange = 150.f;

    UPROPERTY(EditDefaultsOnly, Category = "Combat", meta = (Units = "s"))
    float MeleeCooldown = 0.8f;

    UPROPERTY(EditDefaultsOnly, Category = "Combat")
    TObjectPtr<UAnimMontage> MeleeMontage;

private:
    float NextMeleeTime = 0.f;
    float AttackEndTime = 0.f;
    bool bIsDead = false;
};
cpp
// Source/Arena/ArenaCharacterBase.cpp
#include "ArenaCharacterBase.h"
#include "AbilitySystemBlueprintLibrary.h"
#include "AbilitySystemComponent.h"
#include "ArenaAttributeSet.h"
#include "ArenaGameMode.h"
#include "ArenaTags.h"
#include "Components/CapsuleComponent.h"
#include "GameFramework/CharacterMovementComponent.h"

AArenaCharacterBase::AArenaCharacterBase()
{
    PrimaryActorTick.bCanEverTick = false;                   // nothing here needs Tick

    AbilitySystem = CreateDefaultSubobject<UAbilitySystemComponent>(TEXT("AbilitySystem"));
    AbilitySystem->SetIsReplicated(true);
    AbilitySystem->SetReplicationMode(EGameplayEffectReplicationMode::Minimal);
    Attributes = CreateDefaultSubobject<UArenaAttributeSet>(TEXT("Attributes"));
}

void AArenaCharacterBase::BeginPlay()
{
    Super::BeginPlay();

    AbilitySystem->InitAbilityActorInfo(this, this);
    if (HasAuthority())
    {
        Attributes->InitMaxHealth(StartingHealth);
        Attributes->InitHealth(StartingHealth);
        for (const TSubclassOf<UGameplayAbility>& Ability : StartupAbilities)
        {
            AbilitySystem->GiveAbility(FGameplayAbilitySpec(Ability, 1, INDEX_NONE, this));
        }
    }
    HandleHealthChanged(StartingHealth, StartingHealth);
}

bool AArenaCharacterBase::IsAttacking() const
{
    return GetWorld()->GetTimeSeconds() < AttackEndTime;
}

bool AArenaCharacterBase::TryMeleeAttack()
{
    const float Now = GetWorld()->GetTimeSeconds();
    if (bIsDead || Now < NextMeleeTime) return false;
    NextMeleeTime = Now + MeleeCooldown;
    AttackEndTime = Now + 0.6f;

    if (MeleeMontage)
    {
        PlayAnimMontage(MeleeMontage);
    }

    // Sphere sweep in front of the character, against pawns.
    const FVector Start = GetActorLocation() + GetActorForwardVector() * 50.f;
    const FVector End = GetActorLocation() + GetActorForwardVector() * MeleeRange;
    FCollisionQueryParams Params(SCENE_QUERY_STAT(ArenaMelee), false, this);
    TArray<FHitResult> Hits;
    GetWorld()->SweepMultiByChannel(Hits, Start, End, FQuat::Identity, ECC_Pawn,
                                    FCollisionShape::MakeSphere(60.f), Params);

    TSet<AActor*> Damaged;                                   // one hit per actor, even with several components
    for (const FHitResult& Hit : Hits)
    {
        AActor* Other = Hit.GetActor();
        if (IsValid(Other) && !Damaged.Contains(Other))
        {
            Damaged.Add(Other);
            ApplyDamageTo(Other, MeleeDamage);
        }
    }
    return true;
}

void AArenaCharacterBase::ApplyDamageTo(AActor* Target, float Amount)
{
    UAbilitySystemComponent* TargetASC = UAbilitySystemBlueprintLibrary::GetAbilitySystemComponent(Target);
    if (!TargetASC || !DamageEffectClass || !HasAuthority()) return;

    FGameplayEffectContextHandle Context = AbilitySystem->MakeEffectContext();
    Context.AddSourceObject(this);
    const FGameplayEffectSpecHandle Spec = AbilitySystem->MakeOutgoingSpec(DamageEffectClass, 1.f, Context);
    if (Spec.IsValid())
    {
        Spec.Data->SetSetByCallerMagnitude(TAG_Data_Damage, Amount);
        AbilitySystem->ApplyGameplayEffectSpecToTarget(*Spec.Data.Get(), TargetASC);
    }
}

void AArenaCharacterBase::HandleHealthChanged(float Health, float MaxHealth)
{
    OnHealthChanged.Broadcast(Health, MaxHealth);
}

void AArenaCharacterBase::HandleDeath()
{
    if (bIsDead) return;
    bIsDead = true;
    AbilitySystem->AddLooseGameplayTag(TAG_Status_Dead);     // blocks abilities that list Status.Dead
    AbilitySystem->CancelAllAbilities();

    GetCharacterMovement()->DisableMovement();
    GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision);
    GetMesh()->SetCollisionProfileName(TEXT("Ragdoll"));
    GetMesh()->SetSimulatePhysics(true);                     // ragdoll

    if (AArenaGameMode* GM = GetWorld()->GetAuthGameMode<AArenaGameMode>())
    {
        GM->OnCharacterDied(this);
    }
}

Step 3: The player character

cpp
// Source/Arena/ArenaPlayerCharacter.h
#pragma once

#include "CoreMinimal.h"
#include "ArenaCharacterBase.h"
#include "ArenaPlayerCharacter.generated.h"

class USpringArmComponent;
class UCameraComponent;
class UInputMappingContext;
class UInputAction;
struct FInputActionValue;

UCLASS()
class ARENA_API AArenaPlayerCharacter : public AArenaCharacterBase
{
    GENERATED_BODY()

public:
    AArenaPlayerCharacter();

protected:
    virtual void NotifyControllerChanged() override;
    virtual void SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) override;

    void Move(const FInputActionValue& Value);
    void Look(const FInputActionValue& Value);
    void Attack();
    void Shockwave();

    UPROPERTY(VisibleAnywhere, Category = "Camera")
    TObjectPtr<USpringArmComponent> CameraBoom;

    UPROPERTY(VisibleAnywhere, Category = "Camera")
    TObjectPtr<UCameraComponent> FollowCamera;

    UPROPERTY(EditDefaultsOnly, Category = "Input")
    TObjectPtr<UInputMappingContext> DefaultMappingContext;

    UPROPERTY(EditDefaultsOnly, Category = "Input")
    TObjectPtr<UInputAction> MoveAction;

    UPROPERTY(EditDefaultsOnly, Category = "Input")
    TObjectPtr<UInputAction> LookAction;

    UPROPERTY(EditDefaultsOnly, Category = "Input")
    TObjectPtr<UInputAction> JumpAction;

    UPROPERTY(EditDefaultsOnly, Category = "Input")
    TObjectPtr<UInputAction> AttackAction;

    UPROPERTY(EditDefaultsOnly, Category = "Input")
    TObjectPtr<UInputAction> ShockwaveAction;

    UPROPERTY(EditDefaultsOnly, Category = "Abilities")
    TSubclassOf<UGameplayAbility> ShockwaveAbilityClass;     // GA_Shockwave_BP (also in StartupAbilities)
};
cpp
// Source/Arena/ArenaPlayerCharacter.cpp
#include "ArenaPlayerCharacter.h"
#include "AbilitySystemComponent.h"
#include "Camera/CameraComponent.h"
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "InputActionValue.h"

AArenaPlayerCharacter::AArenaPlayerCharacter()
{
    bUseControllerRotationYaw = false;
    GetCharacterMovement()->bOrientRotationToMovement = true;
    GetCharacterMovement()->RotationRate = FRotator(0.f, 600.f, 0.f);
    GetCharacterMovement()->MaxWalkSpeed = 500.f;

    CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
    CameraBoom->SetupAttachment(RootComponent);
    CameraBoom->TargetArmLength = 450.f;
    CameraBoom->bUsePawnControlRotation = true;

    FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
    FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);

    StartingHealth = 100.f;
    MeleeDamage = 20.f;
    MeleeCooldown = 0.8f;
}

void AArenaPlayerCharacter::NotifyControllerChanged()
{
    Super::NotifyControllerChanged();
    if (APlayerController* PC = Cast<APlayerController>(Controller))
    {
        if (auto* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PC->GetLocalPlayer()))
        {
            Subsystem->AddMappingContext(DefaultMappingContext, 0);
        }
    }
}

void AArenaPlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    UEnhancedInputComponent* Input = CastChecked<UEnhancedInputComponent>(PlayerInputComponent);
    Input->BindAction(MoveAction, ETriggerEvent::Triggered, this, &AArenaPlayerCharacter::Move);
    Input->BindAction(LookAction, ETriggerEvent::Triggered, this, &AArenaPlayerCharacter::Look);
    Input->BindAction(JumpAction, ETriggerEvent::Started, this, &ACharacter::Jump);
    Input->BindAction(JumpAction, ETriggerEvent::Completed, this, &ACharacter::StopJumping);
    Input->BindAction(AttackAction, ETriggerEvent::Started, this, &AArenaPlayerCharacter::Attack);
    Input->BindAction(ShockwaveAction, ETriggerEvent::Started, this, &AArenaPlayerCharacter::Shockwave);
}

void AArenaPlayerCharacter::Move(const FInputActionValue& Value)
{
    if (IsDead()) return;
    const FVector2D Axis = Value.Get<FVector2D>();
    const FRotator Yaw(0.f, GetControlRotation().Yaw, 0.f);
    AddMovementInput(FRotationMatrix(Yaw).GetUnitAxis(EAxis::X), Axis.Y);
    AddMovementInput(FRotationMatrix(Yaw).GetUnitAxis(EAxis::Y), Axis.X);
}

void AArenaPlayerCharacter::Look(const FInputActionValue& Value)
{
    const FVector2D Axis = Value.Get<FVector2D>();
    AddControllerYawInput(Axis.X);
    AddControllerPitchInput(Axis.Y);
}

void AArenaPlayerCharacter::Attack()
{
    TryMeleeAttack();
}

void AArenaPlayerCharacter::Shockwave()
{
    if (ShockwaveAbilityClass)
    {
        AbilitySystem->TryActivateAbilityByClass(ShockwaveAbilityClass);   // fails silently while on cooldown
    }
}

Step 4: The Shockwave ability

The ability commits (which applies the cooldown effect set in its Blueprint child), finds every other character within the radius, damages them through the owner's ApplyDamageTo, and launches them away.

cpp
// Source/Arena/GA_Shockwave.h
#pragma once

#include "CoreMinimal.h"
#include "Abilities/GameplayAbility.h"
#include "GA_Shockwave.generated.h"

UCLASS()
class ARENA_API UGA_Shockwave : public UGameplayAbility
{
    GENERATED_BODY()

public:
    UGA_Shockwave();

    virtual void ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo,
                                 const FGameplayAbilityActivationInfo ActivationInfo,
                                 const FGameplayEventData* TriggerEventData) override;

protected:
    UPROPERTY(EditDefaultsOnly, Category = "Shockwave", meta = (Units = "cm"))
    float Radius = 400.f;

    UPROPERTY(EditDefaultsOnly, Category = "Shockwave")
    float Damage = 35.f;

    UPROPERTY(EditDefaultsOnly, Category = "Shockwave")
    float KnockbackStrength = 900.f;
};
cpp
// Source/Arena/GA_Shockwave.cpp
#include "GA_Shockwave.h"
#include "ArenaCharacterBase.h"
#include "ArenaTags.h"
#include "Engine/OverlapResult.h"

UGA_Shockwave::UGA_Shockwave()
{
    InstancingPolicy = EGameplayAbilityInstancingPolicy::InstancedPerActor;
    NetExecutionPolicy = EGameplayAbilityNetExecutionPolicy::ServerOnly;   // single-player: keep it simple
    ActivationBlockedTags.AddTag(TAG_Status_Dead);
    // CooldownGameplayEffectClass = GE_Shockwave_Cooldown, set in the Blueprint child GA_Shockwave_BP.
}

void UGA_Shockwave::ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo,
                                    const FGameplayAbilityActivationInfo ActivationInfo,
                                    const FGameplayEventData* TriggerEventData)
{
    if (!CommitAbility(Handle, ActorInfo, ActivationInfo))
    {
        EndAbility(Handle, ActorInfo, ActivationInfo, true, true);
        return;
    }

    AArenaCharacterBase* Self = Cast<AArenaCharacterBase>(ActorInfo->AvatarActor.Get());
    if (Self)
    {
        TArray<FOverlapResult> Overlaps;
        FCollisionQueryParams Params(SCENE_QUERY_STAT(ArenaShockwave), false, Self);
        Self->GetWorld()->OverlapMultiByChannel(Overlaps, Self->GetActorLocation(), FQuat::Identity, ECC_Pawn,
                                                FCollisionShape::MakeSphere(Radius), Params);

        TSet<AArenaCharacterBase*> Hit;
        for (const FOverlapResult& Overlap : Overlaps)
        {
            AArenaCharacterBase* Other = Cast<AArenaCharacterBase>(Overlap.GetActor());
            if (!IsValid(Other) || Other->IsDead() || Hit.Contains(Other)) continue;
            Hit.Add(Other);

            Self->ApplyDamageTo(Other, Damage);
            if (!Other->IsDead())
            {
                FVector Away = (Other->GetActorLocation() - Self->GetActorLocation()).GetSafeNormal2D();
                Other->LaunchCharacter(Away * KnockbackStrength + FVector(0.f, 0.f, 300.f), true, true);
            }
        }
    }
    EndAbility(Handle, ActorInfo, ActivationInfo, true, false);
}

FOverlapResult lives in Engine/OverlapResult.h in recent 5.x versions; older ones got it through WorldCollision.h. If the include isn't found, your version predates the split.

Step 5: The enemy, its controller and its Behavior Tree task

cpp
// Source/Arena/ArenaEnemy.h
#pragma once

#include "CoreMinimal.h"
#include "ArenaCharacterBase.h"
#include "ArenaEnemy.generated.h"

UCLASS()
class ARENA_API AArenaEnemy : public AArenaCharacterBase
{
    GENERATED_BODY()

public:
    AArenaEnemy();
};

// Source/Arena/ArenaEnemy.cpp
#include "ArenaEnemy.h"
#include "ArenaAIController.h"
#include "GameFramework/CharacterMovementComponent.h"

AArenaEnemy::AArenaEnemy()
{
    AIControllerClass = AArenaAIController::StaticClass();
    AutoPossessAI = EAutoPossessAI::PlacedInWorldOrSpawned;

    GetCharacterMovement()->MaxWalkSpeed = 300.f;
    // Turn toward the controller's focus (the hero), so melee sweeps point at the target.
    GetCharacterMovement()->bOrientRotationToMovement = false;
    GetCharacterMovement()->bUseControllerDesiredRotation = true;
    GetCharacterMovement()->RotationRate = FRotator(0.f, 360.f, 0.f);
    bUseControllerRotationYaw = false;

    StartingHealth = 150.f;
    MeleeDamage = 12.f;
    MeleeCooldown = 1.2f;
}
cpp
// Source/Arena/ArenaAIController.h
#pragma once

#include "CoreMinimal.h"
#include "AIController.h"
#include "ArenaAIController.generated.h"

class UBehaviorTree;

UCLASS()
class ARENA_API AArenaAIController : public AAIController
{
    GENERATED_BODY()

protected:
    virtual void OnPossess(APawn* InPawn) override;

    UPROPERTY(EditDefaultsOnly, Category = "AI")
    TObjectPtr<UBehaviorTree> BehaviorTree;            // set in BP_ArenaAIController
};

// Source/Arena/ArenaAIController.cpp
#include "ArenaAIController.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "Kismet/GameplayStatics.h"

void AArenaAIController::OnPossess(APawn* InPawn)
{
    Super::OnPossess(InPawn);
    if (BehaviorTree && RunBehaviorTree(BehaviorTree))
    {
        // One enemy, one player: no perception needed. The Grunt always knows where the hero is.
        APawn* Hero = UGameplayStatics::GetPlayerPawn(this, 0);
        GetBlackboardComponent()->SetValueAsObject(TEXT("TargetActor"), Hero);
        SetFocus(Hero);                                // the controller (and so the pawn) faces the hero
    }
}

Because BehaviorTree is an asset chosen in a Blueprint child, set the enemy's AI controller class to that child: in BP_ArenaEnemy's class defaults, AI Controller Class = BP_ArenaAIController. The constructor line above is only the fallback.

cpp
// Source/Arena/BTTask_ArenaMeleeAttack.h
#pragma once

#include "CoreMinimal.h"
#include "BehaviorTree/BTTaskNode.h"
#include "BTTask_ArenaMeleeAttack.generated.h"

UCLASS()
class ARENA_API UBTTask_ArenaMeleeAttack : public UBTTaskNode
{
    GENERATED_BODY()

public:
    UBTTask_ArenaMeleeAttack();

protected:
    virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override;
};

// Source/Arena/BTTask_ArenaMeleeAttack.cpp
#include "BTTask_ArenaMeleeAttack.h"
#include "AIController.h"
#include "ArenaCharacterBase.h"

UBTTask_ArenaMeleeAttack::UBTTask_ArenaMeleeAttack()
{
    NodeName = TEXT("Arena Melee Attack");
}

EBTNodeResult::Type UBTTask_ArenaMeleeAttack::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
    AAIController* AI = OwnerComp.GetAIOwner();
    AArenaCharacterBase* Self = AI ? Cast<AArenaCharacterBase>(AI->GetPawn()) : nullptr;
    if (!Self || Self->IsDead()) return EBTNodeResult::Failed;
    return Self->TryMeleeAttack() ? EBTNodeResult::Succeeded : EBTNodeResult::Failed;
}

The task holds no per-AI state, so the shared node instance is safe.

Step 6: The GameMode

cpp
// Source/Arena/ArenaGameMode.h
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "ArenaGameMode.generated.h"

class AArenaCharacterBase;

UCLASS()
class ARENA_API AArenaGameMode : public AGameModeBase
{
    GENERATED_BODY()

public:
    void OnCharacterDied(AArenaCharacterBase* Dead);

protected:
    UPROPERTY(EditDefaultsOnly, Category = "Arena", meta = (Units = "s"))
    float RestartDelay = 3.f;

private:
    void RestartArena();

    FTimerHandle RestartTimer;
    bool bRoundOver = false;
};

// Source/Arena/ArenaGameMode.cpp
#include "ArenaGameMode.h"
#include "ArenaCharacterBase.h"
#include "Kismet/GameplayStatics.h"

void AArenaGameMode::OnCharacterDied(AArenaCharacterBase* Dead)
{
    if (bRoundOver || !Dead) return;
    bRoundOver = true;

    const bool bPlayerDied = Dead->IsPlayerControlled();
    const FString Result = bPlayerDied ? TEXT("DEFEAT") : TEXT("VICTORY");
    UE_LOG(LogTemp, Display, TEXT("Arena Duel: %s"), *Result);
    if (GEngine)
    {
        GEngine->AddOnScreenDebugMessage(-1, RestartDelay, bPlayerDied ? FColor::Red : FColor::Green, Result);
    }
    GetWorldTimerManager().SetTimer(RestartTimer, this, &AArenaGameMode::RestartArena, RestartDelay, false);
}

void AArenaGameMode::RestartArena()
{
    UGameplayStatics::OpenLevel(this, FName(*UGameplayStatics::GetCurrentLevelName(this)));
}

Build in the IDE (with the editor closed), then open the editor.

Step 7: Editor steps

Gameplay effects (Content Browser → Add → Blueprint Class → GameplayEffect):

  1. GE_Damage: Duration Policy Instant; one modifier: Attribute ArenaAttributeSet.IncomingDamage, Modifier Op Add, Magnitude Calculation Type Set by Caller with Data Tag Data.Damage.
  2. GE_Shockwave_Cooldown: Duration Policy Has Duration, 5 seconds; add the Grant Tags to Target Actor component (the Target Tags GE component in UE 5.3+; older versions have a Granted Tags field) with Cooldown.Shockwave.

Ability: create GA_Shockwave_BP as a Blueprint child of GA_Shockwave; set Cooldown Gameplay Effect Class = GE_Shockwave_Cooldown.

Input (as in Enhanced Input): IA_Move, IA_Look, IA_Jump, plus IA_Attack (bool, Left Mouse Button / Gamepad Right Trigger) and IA_Shockwave (bool, E / Gamepad Face Button Left), all in IMC_Arena.

Characters:

  1. BP_ArenaPlayer (child of ArenaPlayerCharacter): mesh SKM_Manny (or the template's mannequin), position Z −90, rotation yaw −90; Anim Class: the template's animation Blueprint; the six input assets; Damage Effect Class = GE_Damage; Startup Abilities = [GA_Shockwave_BP]; Shockwave Ability Class = GA_Shockwave_BP; optionally a punch montage as Melee Montage.
  2. BP_ArenaEnemy (child of ArenaEnemy): the same mannequin with a different material instance (red); Damage Effect Class = GE_Damage; AI Controller Class = BP_ArenaAIController.

AI:

  1. Blackboard BB_Arena with one key TargetActor (Object, base class Actor).
  2. Behavior Tree BT_Arena using BB_Arena: Root → Sequence with a Blackboard decorator (TargetActor Is Set), children Move To (Blackboard Key TargetActor, Acceptable Radius 120), Arena Melee Attack, Wait 0.3 s.
  3. BP_ArenaAIController (child of ArenaAIController): Behavior Tree = BT_Arena.

Level and mode:

  1. A new level L_Arena: a floor (a scaled cube, 30×30 m), four walls, a Directional Light, Sky Atmosphere and Sky Light (or Window → Env. Light Mixer), a Player Start on one side, BP_ArenaEnemy on the other, and a Nav Mesh Bounds Volume covering the floor (press P to check it's green).
  2. BP_ArenaGameMode (child of ArenaGameMode): Default Pawn Class = BP_ArenaPlayer.
  3. World Settings → GameMode Override = BP_ArenaGameMode; Project Settings → Maps & Modes: default map L_Arena.

Optional health bars: a WBP_Health widget with a Progress Bar; in its Event Construct, get the owning character and Assign On Health Changed to set the bar's percent to Health / MaxHealth. Add it to the viewport from BP_ArenaPlayer's BeginPlay (for the hero), or as a WidgetComponent above the Grunt's head.

Press Play. The Grunt walks over and swings every 1.2 s; left-click to hit back, E for the shockwave. While the cooldown runs, showdebug abilitysystem in the console shows the Cooldown.Shockwave tag on the hero.

Step 8: The combat rules, as a runnable model

Before tuning numbers in the editor, it pays to have the rules in a form you can run in a second. This model uses the same values as the classes above (health 100 vs 150, melee 20 / 0.8 s vs 12 / 1.2 s, ranges, shockwave 35 damage in 400 cm with a 5 s cooldown tag), on a one-dimensional arena at 10 updates per second. The Grunt follows its Behavior Tree (move to within 120 cm, then attack). The hero stands still and presses buttons from a script.

cpp · try it yourself
#include <algorithm>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <map>
#include <string>

// The Arena Duel combat rules, on a 1D arena (positions in cm), stepped at 10 Hz.
struct Fighter {
    std::string Name;
    double X, Health, MaxHealth, Speed;
    double MeleeDamage, MeleeRange, MeleeCooldown;
    double NextMeleeTime = 0;
    bool Dead = false;
};

struct Rules {
    double ShockwaveDamage = 35, ShockwaveRadius = 400, ShockwaveCooldown = 5, Knockback = 600;
    double ArenaHalfWidth = 1500;
};

double Now = 0;
std::map<std::string, double> CooldownTags;              // tag -> expiry time (GAS cooldown effects)

void Log(const std::string& msg) { std::cout << "t=" << std::setw(4) << Now << "  " << msg << "\n"; }

// ApplyDamageTo -> GE_Damage (SetByCaller) -> IncomingDamage -> PostGameplayEffectExecute
void ApplyDamage(Fighter& target, double amount, const std::string& source) {
    if (target.Dead) return;
    target.Health = std::clamp(target.Health - amount, 0.0, target.MaxHealth);
    std::cout << "t=" << std::setw(4) << Now << "  " << source << " hits " << target.Name << " for " << amount
              << " -> " << target.Health << "/" << target.MaxHealth << "\n";
    if (target.Health <= 0) { target.Dead = true; Log(target.Name + " dies"); }
}

bool TryMelee(Fighter& self, Fighter& other) {
    if (self.Dead || Now < self.NextMeleeTime - 1e-9) return false;
    if (std::fabs(self.X - other.X) > self.MeleeRange) return false;
    self.NextMeleeTime = Now + self.MeleeCooldown;
    ApplyDamage(other, self.MeleeDamage, self.Name + " melee");
    return true;
}

bool TryShockwave(Fighter& self, Fighter& other, const Rules& r) {
    if (self.Dead) return false;
    if (CooldownTags.count("Cooldown.Shockwave") && Now < CooldownTags["Cooldown.Shockwave"] - 1e-9) {
        Log("Shockwave blocked by tag Cooldown.Shockwave");
        return false;
    }
    CooldownTags["Cooldown.Shockwave"] = Now + r.ShockwaveCooldown;     // CommitAbility
    double d = other.X - self.X;
    if (std::fabs(d) <= r.ShockwaveRadius) {
        ApplyDamage(other, r.ShockwaveDamage, "Shockwave");
        if (!other.Dead) {
            other.X = std::clamp(other.X + (d >= 0 ? 1 : -1) * r.Knockback, -r.ArenaHalfWidth, r.ArenaHalfWidth);
            Log(other.Name + " knocked back to x=" + std::to_string((int)other.X));
        }
    } else {
        Log("Shockwave hits nothing");
    }
    return true;
}

int main() {
    std::cout << std::fixed << std::setprecision(1);
    Rules rules;
    Fighter player{"Player", -600, 100, 100, 500, 20, 150, 0.8};
    Fighter enemy{"Grunt", 600, 150, 150, 300, 12, 150, 1.2};

    // Player script: update step (0.1 s each) -> button pressed.
    std::map<int, std::string> input = {{20, "attack"}, {30, "shockwave"}, {35, "shockwave"},
                                        {60, "attack"}, {70, "attack"}, {80, "attack"}, {90, "shockwave"},
                                        {105, "attack"}, {110, "attack"}};
    for (int step = 0; step <= 200 && !player.Dead && !enemy.Dead; step++) {
        Now = step * 0.1;
        // Enemy AI (Behavior Tree): MoveTo(target, acceptance 120) then MeleeAttack.
        double gap = player.X - enemy.X;
        if (std::fabs(gap) > 120) enemy.X += std::copysign(std::min(enemy.Speed * 0.1, std::fabs(gap) - 120), gap);
        else TryMelee(enemy, player);
        // Player: holds still and acts on the script.
        if (input.count(step)) {
            const std::string& a = input[step];
            if (a == "attack" && !TryMelee(player, enemy)) Log("Player attack: out of range or on cooldown");
            if (a == "shockwave") TryShockwave(player, enemy, rules);
        }
    }
    std::cout << (enemy.Dead ? "VICTORY" : player.Dead ? "DEFEAT" : "time out") << " (Player " << player.Health
              << " HP, Grunt " << enemy.Health << " HP)\n";
}
t= 2.0  Player attack: out of range or on cooldown
t= 3.0  Shockwave hits Grunt for 35.0 -> 115.0/150.0
t= 3.0  Grunt knocked back to x=270
t= 3.5  Shockwave blocked by tag Cooldown.Shockwave
t= 5.6  Grunt melee hits Player for 12.0 -> 88.0/100.0
t= 6.0  Player melee hits Grunt for 20.0 -> 95.0/150.0
t= 6.8  Grunt melee hits Player for 12.0 -> 76.0/100.0
t= 7.0  Player melee hits Grunt for 20.0 -> 75.0/150.0
t= 8.0  Grunt melee hits Player for 12.0 -> 64.0/100.0
t= 8.0  Player melee hits Grunt for 20.0 -> 55.0/150.0
t= 9.0  Shockwave hits Grunt for 35.0 -> 20.0/150.0
t= 9.0  Grunt knocked back to x=120
t=10.5  Player attack: out of range or on cooldown
t=11.0  Player melee hits Grunt for 20.0 -> 0.0/150.0
t=11.0  Grunt dies
VICTORY (Player 64.0 HP, Grunt 0.0 HP)

Read it like a playtest log:

  • The first melee press at 2.0 s missed because the Grunt was still far away. The shockwave at 3.0 s hit and threw it back, and the second press at 3.5 s was blocked by the cooldown tag, exactly as TryActivateAbilityByClass fails while Cooldown.Shockwave is present.
  • In melee range, the hero trades 20 damage per 0.8 s against 12 per 1.2 s, so the hero wins any straight exchange. The second shockwave at 9.0 s left the Grunt on 20 HP.
  • Try changing the numbers: give the Grunt 300 HP, or set MeleeCooldown to 0.6, or delete the second shockwave from the script, and see whether the duel is still winnable. That is balancing, done in seconds instead of play sessions.

Extensions

  1. Hit timing from animation: apply melee damage from an Anim Notify State window (ANS_HitWindow) instead of instantly in TryMeleeAttack (Montages).
  2. Perception: replace the "always knows" line in OnPossess with sight perception, and add an Investigate branch (AIController).
  3. A cooldown UI: listen for the Cooldown.Shockwave tag with AbilitySystem->RegisterGameplayTagEvent(TAG_Cooldown_Shockwave) and grey out an icon while it exists.
  4. Multiplayer: move the ASC to a PlayerState for players, call InitAbilityActorInfo in PossessedBy/OnRep_PlayerState, make Shockwave LocalPredicted, send melee through a Server RPC, and replicate the attributes with GetLifetimeReplicatedProps as in the GAS lesson.
  5. More enemies: a spawner that uses a timer and a wave data asset; switch the win condition to "all waves cleared".

Test yourself

Why does damage go through GE_Damage and the IncomingDamage meta attribute instead of setting Health directly?

  1. Setting Health directly doesn't compile
  2. All damage rules (clamping, death, future armor) live in one place in the attribute set, and GAS handles replication and prediction
  3. Gameplay effects are faster
  4. Blueprints can't read Health

Why does the second shockwave press at 3.5 s fail?

  1. The Grunt was out of range
  2. The cooldown effect granted Cooldown.Shockwave for 5 s, which blocks activation
  3. The player was dead
  4. Abilities can only be used once

Where must the enemy's Behavior Tree asset be assigned for the C++ OnPossess to run it?

  1. In the enemy's constructor
  2. On BP_ArenaAIController, which BP_ArenaEnemy uses as its AI Controller Class
  3. In the GameMode
  4. In Project Settings