Unreal - AI에게 HP 프로그래스바 붙히기

2025. 5. 9. 13:56·Unreal5 프로젝트 다이어리

AI가 Perception으로 Player를 인지하면 

AI머리위에 HP에 비례한 ProgressBar를 가지고있는 위젯을 띄워보겠습니다

 

UserWidget을 상속받은 위젯을 만들어주겠습니다

 

이름은 SkeletonHPBarWidget이라고 이름지어주었습니다

 

해당c++를 상속받은 블루프린트를 만들어주고

위젯을 해당 그림과 같이 설정해주었습니다

Custom / Width = 150, Height = 100 , 앵커 중앙입니다

해당 위젯을 AI가 가지기 위해 AI에서 위젯컴포넌트형식으로 달아주겠습니다

 

.h에서 UWidgetComponent를 선언

UPROPERTY(EditAnywhere, Category = "MySettings")
class UWidgetComponent* hpFloatingWidget;

 

생성자에서 만들어주고 위치를 맞춰주고 위젯의 위치를 World -> Screen으로 변동해줍니다

만약 World인 상태로 둔다면 AI가 회전하면 프로그래스바위젯 또한 같이 회전합니다

//floatingWidget
hpFloatingWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("floatingWidget"));
hpFloatingWidget->SetupAttachment(RootComponent);
hpFloatingWidget->SetRelativeLocation(FVector(0, 0, 125));
hpFloatingWidget->SetWorldScale3D(FVector(1.0, 0.23, 0.03));
hpFloatingWidget->SetWidgetSpace(EWidgetSpace::Screen);

 

생성한 위젯컴포넌트에서 위젯 클래스를 만들어둔 위젯블루프린트를 할당해줍니다

 

잘 달린것을 확인할수있습니다

 

그럼 이 프로그래스바를 AI의 currentHp와 연동시켜보겠습니다

위젯의 c++에서 ProgressBar를 바인딩해줍니다

public:
	UPROPERTY(meta = (BindWidget))
	class UProgressBar* pb_healthBar;

 

만든 변수명과 동일하게 이름을 변경해주고 변수여부를 체크해주겠습니다

 

ProgressBar를 0에서 1로 값을 받아오고

업데이시키는 함수를 만들겠습니다

필요한 헤더또한 추가해주었습니다

#include "Components/ProgressBar.h"
UFUNCTION()
void updateHpBar(float currentHp, float maxHp);
void USkeletonHPBarWidget::updateHpBar(float currentHp, float maxHp)
{
	if (maxHp <= 0.0f)
	{
		return;
	}
	currentHp = FMath::Max(currentHp, 0.0f);
	if (IsValid(pb_healthBar))
	{
		pb_healthBar->SetPercent(FMath::Clamp(currentHp / maxHp, 0.0f, 1.0f));
	}
}

 

해당 UpdateHpBar 함수가 실행되는 그 값에 따라 현재 프로그래스바가 업데이트됩니다

프로그래스바가 업데이트 해야할 시점은 상시 AI가 업데이트해야합니다

 

AI의 Tick에서 업데이트시켜주겠습니다

현재 AI는 위젯컴포넌트를 생성자에서 이미 만들어놨습니다

 

skeletonHpBarWidget을 선언후 BeginPlay에서 캐스팅을 해주겠습니다

캐스팅은 만들어놓은 위젯컴포넌트에서 GetUserWidgetObject()로 캐스팅이 가능합니다

class USkeletonHPBarWidget* skeletonHpBarWidget;
skeletonHpBarWidget = Cast<USkeletonHPBarWidget>(hpFloatingWidget->GetUserWidgetObject());

 

tick에서 AI의 max와 currentHp값을 넣어주어 업데이트 시켜주겠습니다

 

AI의 Tick에서 AI의 currentHp값에대한 값을 넘겨받아 progressbar가 알맞는

수치를 반영하는것을확인할수있습니다

 

디테일을 추가해주겠습니다

AI의 HP가 70% ~ 100% 면 프로그래스바 색상이 진하고 어두운 빨간색

40% ~ 69%면 주황색

1% ~ 39%면 밝은빨강으로 변경해보도록 하겠습니다

 

UpdateHpBar함수를 수정해주겠습니다

barPercent로 0부터 1까지 비율을 계산한다음 FLinearColor로 색상을 변경했습니다

 

만약 프로그래스바가 수동으로 색상이 설정이 되어있다면 색상이 변하지않습니다

색상을 1 1 1 1로 기본값으로 유지해주세요

void USkeletonHPBarWidget::updateHpBar(float currentHp, float maxHp)
{
	if (maxHp <= 0.0f)
	{
		return;
	}
	currentHp = FMath::Max(currentHp, 0.0f);
	if (IsValid(pb_healthBar))
	{
        float barPercent = FMath::Clamp(currentHp / maxHp, 0.0f, 1.0f);
        pb_healthBar->SetPercent(barPercent);

        FLinearColor barColor;
        if (barPercent >= 0.7f)
        {
            //진하고 빨강
            barColor = FLinearColor(0.6f, 0.0f, 0.0f);
        }
        else if (barPercent >= 0.4f)
        {
            //주황
            barColor = FLinearColor(1.0f, 0.5f, 0.0f);
        }
        else
        {
            //밝은 빨강
            barColor = FLinearColor(1.0f, 0.05f, 0.05f);
        }

        pb_healthBar->SetFillColorAndOpacity(barColor);
	} 
}

 

중간결과물

 

프로그래스바가 상시로 떠있으면 곤란합니다

AI 의 Perception에 탐지되면 보이고 탐지되지않으면 보이지않게해보겠습니다.

그리고 AI가 죽으면 보이지않게해보겠습니다

 

AI Perception은 컨트롤러에 있습니다

컨트롤러에서 캐스팅할 skeleton을 선언

 

탐지가되면 보이고 탐지가안되면 보이지않게 설정해주었습니다

죽으면 widget을 사라지게코드도 수정해주었습니다

최종 progressbar 함수입니다

void USkeletonHPBarWidget::updateHpBar(float currentHp, float maxHp)
{
	if (maxHp <= 0.0f)
	{
		return;
	}
	currentHp = FMath::Max(currentHp, 0.0f);
	if (IsValid(pb_healthBar))
	{
        float barPercent = FMath::Clamp(currentHp / maxHp, 0.0f, 1.0f);
        pb_healthBar->SetPercent(barPercent);

        FLinearColor barColor;
        if (barPercent >= 0.7f)
        {
            //진하고 빨강
            barColor = FLinearColor(0.6f, 0.0f, 0.0f);
        }
        else if (barPercent >= 0.4f)
        {
            //주황
            barColor = FLinearColor(1.0f, 0.5f, 0.0f);
        }
        else
        {
            //밝은 빨강
            barColor = FLinearColor(1.0f, 0.05f, 0.05f);
        }

        pb_healthBar->SetFillColorAndOpacity(barColor);
	} 
    if (currentHp <= 0.0f)
    {
        pb_healthBar->SetVisibility(ESlateVisibility::Collapsed);
    }
}

ESlateVisibility::Collapsed로 완전히 삭제시킵니다

 

최종결과물

'Unreal5 프로젝트 다이어리' 카테고리의 다른 글

Unreal - AI의 회피 알고리즘( RVO )  (0) 2025.05.10
Uneal - EQS Strafe이동  (0) 2025.05.10
Unreal - ProjectTile을 사용한 원거리 AI 만들기  (0) 2025.05.09
Unreal - Behavior Tree(5) 스폰 / 디스폰  (0) 2025.05.08
Unreal - Dissolve Material  (0) 2025.05.08
'Unreal5 프로젝트 다이어리' 카테고리의 다른 글
  • Unreal - AI의 회피 알고리즘( RVO )
  • Uneal - EQS Strafe이동
  • Unreal - ProjectTile을 사용한 원거리 AI 만들기
  • Unreal - Behavior Tree(5) 스폰 / 디스폰
lucodev
lucodev
커피와 노트북 그리고 개발
  • lucodev
    루코 개발테이블
    lucodev
  • 전체
    오늘
    어제
    • 분류 전체보기 (125) N
      • Unreal5 프로젝트 다이어리 (73)
      • Unreal5 프로젝트 다이어리2 (5) N
      • Unreal 팁 (8)
      • Unreal 디버깅 (8)
      • C++ 프로그래머스 다이어리 (23) N
        • Stack (3)
        • Hash (4)
        • Heap (2)
        • Sort (3) N
      • 코드 개인보관함 (8) N
  • 인기 글

  • 최근 글

  • 최근 댓글

  • 링크

  • 공지사항

  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 태그

    unreal sequence
    언리얼 비헤이비어트리
    언리얼 behaviortree
    unreal loading
    언리얼 시퀀스
    언리얼
    unreal 시퀀스
    언리얼 로딩창
    언리얼 motionmatching
    언리얼 페이드 아웃
    언리얼 모션매칭
    언리얼 foot step
    언리얼 behavior tree
    언리얼 look at
    unreal 모션매칭
    언리얼 컷씬
    unreal 로딩
    unreal 컷씬
    unreal look at
    언리얼 로딩
  • hELLO· Designed By정상우.v4.10.3
lucodev
Unreal - AI에게 HP 프로그래스바 붙히기
상단으로

티스토리툴바