728x90
728x90
안녕하세요!
언리얼 엔진 5 (UE5)에서 캐릭터와 다른 액터 사이의 가장 가까운 점을 구하는 C++ 코드를 소개하고 자세하게 설명드리겠습니다. 이전에는 가장 가까운 액터를 찾는 방법을 알아보았다면, 이번에는 특정 액터의 콜리전 메시에서 캐릭터와 가장 가까운 점의 좌표를 정확하게 얻는 방법을 다룹니다.
핵심 개념: UPrimitiveComponent 와 GetClosestPointOnCollision()
이 기능을 구현하는 핵심은 UPrimitiveComponent와 GetClosestPointOnCollision() 함수를 사용하는 것입니다. 모든 액터가 콜리전을 가지는 것은 아니기 때문에, 먼저 액터가 콜리전 컴포넌트를 가지고 있는지 확인하는 것이 중요합니다.
C++ 코드
// 캐릭터의 헤더 파일 (.h)
#pragma once
UCLASS()
class MYPROJECT_API AMyCharacter : public ACharacter
{
GENERATED_BODY()
public:
AMyCharacter();
protected:
virtual void BeginPlay() override;
public:
virtual void Tick(float DeltaTime) override;
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
UFUNCTION(BlueprintPure, Category = "Distance")
FVector GetClosestPointOnActor(AActor* OtherActor, float& OutDistance);
private:
// 필요한 경우 여기에 개인 변수를 추가
};
// 캐릭터의 소스 파일 (.cpp)
AMyCharacter::AMyCharacter()
{
PrimaryActorTick.bCanEverTick = true;
}
void AMyCharacter::BeginPlay()
{
Super::BeginPlay();
}
void AMyCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
FVector AMyCharacter::GetClosestPointOnActor(AActor* OtherActor, float& OutDistance)
{
if (!OtherActor)
{
OutDistance = MAX_FLT;
return FVector::ZeroVector;
}
UPrimitiveComponent* OtherActorPrimitive = Cast<UPrimitiveComponent>(OtherActor->GetComponentByClass(UPrimitiveComponent::StaticClass()));
if (!OtherActorPrimitive)
{
UE_LOG(LogTemp, Warning, TEXT("액터 %s에는 Primitive Component가 없습니다!"), *OtherActor->GetName());
OutDistance = MAX_FLT;
return OtherActor->GetActorLocation(); // 콜리전이 없을 경우 액터 위치 반환
}
FVector MyLocation = GetActorLocation();
FVector ClosestPoint = OtherActorPrimitive->GetClosestPointOnCollision(MyLocation);
OutDistance = FVector::Dist(MyLocation, ClosestPoint);
return ClosestPoint;
}
코드 설명
- GetClosestPointOnCollision(MyLocation): 이 함수가 핵심입니다. 캐릭터의 위치(MyLocation)를 입력으로 받아, 액터의 콜리전 메시에서 가장 가까운 점을 반환합니다.
- 오류 처리: OtherActor 또는 OtherActorPrimitive가 유효하지 않을 경우를 대비하여 오류 처리가 추가되었습니다. 이를 통해 예기치 않은 크래시를 방지할 수 있습니다.
- 콜리전이 없는 경우: 만약 대상 액터에 콜리전 컴포넌트가 없다면, 액터의 위치를 대신 반환하도록 처리했습니다.
사용 예시
C++:
AActor* ActorToGetClosestPoint = ...; // 대상 액터 참조
float DistanceToClosestPoint;
FVector ClosestPoint = GetClosestPointOnActor(ActorToGetClosestPoint, DistanceToClosestPoint);
if (ActorToGetClosestPoint)
{
UE_LOG(LogTemp, Warning, TEXT("액터 %s 의 가장 가까운 점: %s, 거리: %f"), *ActorToGetClosestPoint->GetName(), *ClosestPoint.ToString(), DistanceToClosestPoint);
// ClosestPoint 를 활용한 로직 구현
// 예: 캐릭터와 가장 가까운 점 사이에 선 긋기, 이펙트 생성 등
}
블루프린트:
블루프린트에서도 C++ 함수를 노드로 쉽게 사용할 수 있습니다.
- 대상 액터에 대한 변수를 생성합니다.
- GetClosestPointOnActor 함수를 호출합니다.
- OutDistance와 반환 값 (가장 가까운 점의 FVector)을 활용합니다.
추가 팁 및 주의 사항
- 성능: GetClosestPointOnCollision()은 비교적 효율적이지만, 많은 액터에 대해 매 프레임마다 이 함수를 호출하는 것은 성능에 부담을 줄 수 있습니다. 필요에 따라 호출 빈도를 조절하거나, 더 최적화된 방법을 고려해야 합니다.
- 복잡한 콜리전: 복잡한 모양의 콜리전을 가진 액터의 경우, GetClosestPointOnCollision()이 완벽하게 정확하지 않을 수 있습니다. 하지만 대부분의 경우 충분히 정확한 근사값을 제공합니다.
- 디버깅: DrawDebugPoint 함수를 사용하여 찾은 가장 가까운 점을 시각적으로 확인할 수 있습니다.
728x90
반응형
'프로그래밍' 카테고리의 다른 글
언리얼 엔진 5 (UE5) FRotator → FQuat 변환 방법 (0) | 2025.03.06 |
---|---|
언리얼 엔진 5: 월드 파티션 환경에서 TeleportTo 시 액터 복제 (0) | 2025.02.20 |
UE5 네트워크 최적화 : Net Cull Distance 분석 및 설정(코드 예제 수정) (0) | 2025.01.21 |
언리얼 엔진 5 (UE5)에서 월드 시간과 델타 시간 초 단위로 얻기 (C++ 및 블루프린트) (1) | 2025.01.13 |
UE5에서 두 벡터 사이의 각도 구하기 (자세한 설명 + 내적의 의미) (0) | 2025.01.11 |