2. near과 far에 해당하는 위젯 타입을 블루프린트에서 설정할 수 있도록 클래스 타입 변수를 설정해두고,
각 위젯 컴포넌트의 위젯 클래스를 설정하게 한다.
또한 위젯의 space를 스크린으로 지정해둔다.
// UInteractionComponent.h
UPROPERTY(EditAnywhere, Category = "UI")
TSubclassOf<UUserWidget> NearWidgetClass;
UPROPERTY(EditAnywhere, Category = "UI")
TSubclassOf<UUserWidget> FarWidgetClass;
// UInteractionComponent.cpp
// Set widget classes
if (NearWidgetClass)
{
NearWidgetComponent->SetWidgetClass(NearWidgetClass);
}
if (FarWidgetClass)
{
FarWidgetComponent->SetWidgetClass(FarWidgetClass);
}
// Set widget space to screen
NearWidgetComponent->SetWidgetSpace(EWidgetSpace::Screen);
FarWidgetComponent->SetWidgetSpace(EWidgetSpace::Screen);
3. 설정한 값과 거리를 비교하여 설정한 값보다 가까우면 near 멀면 far위젯 컴포넌트가 보일 수 있도록 한다.
void UInteractionUIComponent::SetVisibilityBasedOnDistance(APawn* PlayerPawn)
{
if (false == IsVisible())
{
NearWidgetComponent->SetVisibility(false);
FarWidgetComponent->SetVisibility(false);
return;
}
// Calculate distance between player controller and this scene component
FVector PlayerLocation = PlayerPawn->GetActorLocation();
FVector SceneComponentLocation = GetComponentLocation();
float Distance = FVector::Distance(PlayerLocation, SceneComponentLocation);
// Toggle widget visibility based on distance threshold
if (Distance < DistanceThreshold)
{
// Player is near, show near widget and hide far widget
NearWidgetComponent->SetVisibility(true);
FarWidgetComponent->SetVisibility(false);
}
else
{
// Player is far, hide near widget and show far widget
NearWidgetComponent->SetVisibility(false);
FarWidgetComponent->SetVisibility(true);
}
}