Unreal Engine에서 Detour 기반의 Crowd Simulation 기능을 확장하고 싶을 때, UCrowdFollowingComponent와 UCrowdManager를 상속받아 커스텀 클래스를 만드는 것은 좋은 접근 방식입니다. 이는 특히 여러 AgentRadius를 사용하면서도 각기 다른 크기의 캐릭터가 자연스럽게 경로를 탐색하고 서로를 회피하도록 구성할 때 유용합니다.
아래는 효과적인 구현 방식에 대한 전체적인 가이드라인과 구조입니다.
🧩 1. UCrowdManager 상속받는 커스텀 클래스 (예: UNavCrowdManager)
목적:
- 각기 다른 AgentRadius를 가진 Agent를 관리
- DetourCrowd의
dtCrowd 객체를 커스터마이징
- 각 Agent의 설정 (반지름, 속도 등)을 관리
구현 예시 (헤더 파일):
#pragma once
#include "CrowdManager.h"
#include "NavCrowdManager.generated.h"
UCLASS()
class YOURMODULE_API UNavCrowdManager : public UCrowdManager
{
GENERATED_BODY()
public:
virtual void InitializeCrowd() override;
// 특정 AgentRadius를 기준으로 AgentType을 등록
UFUNCTION(BlueprintCallable, Category = "Crowd")
int32 RegisterAgentType(float AgentRadius, float MaxAcceleration, float MaxSpeed);
// AgentRadius에 따라 적절한 AgentType을 선택
int32 FindBestAgentType(float AgentRadius);
};
구현 예시 (소스 파일):
#include "NavCrowdManager.h"
#include "DetourCrowd.h"
#include "DetourCommon.h"
void UNavCrowdManager::InitializeCrowd()
{
Super::InitializeCrowd();
// 초기화 후 필요한 AgentType을 등록
RegisterAgentType(20.0f, 800.0f, 400.0f); // 작은 에이전트
RegisterAgentType(40.0f, 600.0f, 300.0f); // 중간 에이전트
RegisterAgentType(60.0f, 400.0f, 200.0f); // 큰 에이전트
}
int32 UNavCrowdManager::RegisterAgentType(float AgentRadius, float MaxAcceleration, float MaxSpeed)
{
dtCrowd* Crowd = GetCrowd();
if (!Crowd) return -1;
dtCrowdAgentParams Params;
FMemory::Memzero(&Params, sizeof(Params));
Params.radius = AgentRadius;
Params.height = 100.0f; // 필요에 따라 설정
Params.maxAcceleration = MaxAcceleration;
Params.maxSpeed = MaxSpeed;
Params.collisionQueryRange = AgentRadius * 2.0f;
Params.pathOptimizationRange = 20.0f;
Params.updateFlags = DT_CROWD_ANTICIPATE_TURNS | DT_CROWD_OBSTACLE_AVOIDANCE | DT_CROWD_SEPARATION;
Params.obstacleAvoidanceType = 3; // 보통 3이 가장 정교한 회피
Params.separationWeight = 1.0f;
return Crowd->addAgentType(&Params);
}
int32 UNavCrowdManager::FindBestAgentType(float AgentRadius)
{
// 간단히 AgentRadius 기준으로 가장 가까운 AgentType 선택
// 실제 구현 시 더 정교한 로직 필요
for (int32 i = 0; i < GetCrowd()->getAgentTypesCount(); ++i)
{
const dtCrowdAgentParams* Params = GetCrowd()->getAgentType(i);
if (AgentRadius <= Params->radius + KINDA_SMALL_NUMBER)
{
return i;
}
}
return -1; // 없으면 기본 타입
}
🧩 2. UCrowdFollowingComponent 상속받는 커스텀 클래스 (예: UCustomCrowdFollowingComponent)
목적:
- 각각의 캐릭터가 자신에 맞는 AgentRadius를 기반으로 Crowd 시뮬레이션에 등록
- 매 프레임마다 위치/회전 업데이트
- 필요 시 이동 경로 재설정
구현 예시 (헤더):
#pragma once
#include "CrowdFollowingComponent.h"
#include "CustomCrowdFollowingComponent.generated.h"
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class YOURMODULE_API UCustomCrowdFollowingComponent : public UCrowdFollowingComponent
{
GENERATED_BODY()
public:
UCustomCrowdFollowingComponent();
UPROPERTY(EditAnywhere, Category = "Crowd")
float AgentRadius = 40.0f;
virtual void InitializeAgent() override;
virtual void UpdateAgent() override;
};
구현 예시 (소스):
#include "CustomCrowdFollowingComponent.h"
#include "NavCrowdManager.h"
#include "GameFramework/Character.h"
void UCustomCrowdFollowingComponent::InitializeAgent()
{
UNavCrowdManager* CrowdManager = Cast<UNavCrowdManager>(GetCrowdManager());
if (CrowdManager)
{
int32 AgentTypeID = CrowdManager->FindBestAgentType(AgentRadius);
if (AgentTypeID != -1)
{
AgentID = CrowdManager->AddAgent(GetOwner()->GetActorLocation(), AgentTypeID, this);
}
}
}
void UCustomCrowdFollowingComponent::UpdateAgent()
{
if (AgentID == INDEX_NONE) return;
UNavCrowdManager* CrowdManager = Cast<UNavCrowdManager>(GetCrowdManager());
if (CrowdManager)
{
const dtCrowdAgent* Agent = CrowdManager->GetAgent(AgentID);
if (Agent && dtCrowdAgent::DT_CROWD_AGENT_STATE_ACTIVE == Agent->state)
{
// 위치 업데이트
ACharacter* Owner = Cast<ACharacter>(GetOwner());
if (Owner)
{
FVector NewLocation(Agent->nposition[0], Agent->nposition[2], Agent->nposition[1]);
Owner->SetActorLocation(NewLocation);
// 방향 업데이트
FRotator NewRotation = Owner->GetActorRotation();
NewRotation.Yaw = FMath::RadiansToDegrees(Agent->desiredDirection[0]);
Owner->SetActorRotation(NewRotation);
}
}
}
}
🧠 핵심 포인트 요약
| 항목 | 설명 |
|---|
| UCrowdManager 상속 | Detour의 dtCrowd를 관리하고, 여러 AgentType을 등록 |
| UCrowdFollowingComponent 상속 | 각 캐릭터가 자신의 AgentRadius에 맞는 설정으로 등록 및 업데이트 |
| AgentType 관리 | dtCrowd::addAgentType()으로 다양한 Agent 파라미터를 등록 |
| Agent Radius 기준 선택 | FindBestAgentType()으로 가장 가까운 AgentType 선택 |
| 실시간 위치 업데이트 | UpdateAgent()에서 dtCrowdAgent 상태를 읽고 캐릭터 위치/회전 업데이트 |
✅ 참고 사항
dtCrowd는 Recast/Detour 라이브러리 기반으로, dtCrowdAgent는 시뮬레이션 내에서 경로를 계산하고 충돌 회피를 처리합니다.
UCrowdManager는 Engine에 내장된 CrowdManagerComponent에 연결되어 있어, GetCrowd()를 통해 dtCrowd 객체를 접근 가능합니다.
- Blueprint에서도 사용 가능하게 하려면
UFUNCTION(BlueprintCallable) 등을 활용해 노출하세요.
🧪 테스트 및 디버깅
- Detour Debug Draw 기능을 활성화하여 Crowd 시뮬레이션 상태를 시각화할 수 있습니다.
- 여러 캐릭터에 다른
AgentRadius를 적용하고, 서로 다른 크기의 Agent들이 충돌 없이 자연스럽게 이동하는지 확인하세요.
필요하다면, Blueprint에서 각 캐릭터에 CustomCrowdFollowingComponent를 붙이고, AgentRadius를 조절해서 테스트해보세요.
필요한 추가 기능 (예: 경로 재설정, 장애물 회피 강화 등)이 있다면 알려주세요!