chakokuのブログ(rev4)

テック・コミック・DTM・・・ごくまれにチャリ

UE5 tutorial. カウントダウンして爆発

引き続き、Tutorialをやってみる。カウントダウンして爆発効果になるやつ。

掲示されているサンプルを打ち込んでコンパイルするとエラーになった。自分のやった修正方法が正しいのかわからないが、エラー回避できるように少し修正
file:Countdown.h

#pragma once

//#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Runtime/Engine/Classes/Components/TextRenderComponent.h"
#include "Countdown.generated.h"

UCLASS()
class TEST_CPP3_API ACountdown : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	ACountdown();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	UPROPERTY(EditAnywhere)
	int32 CountdownTime;

	UTextRenderComponent* CountdownText;

	void UpdateTimerDisplay();
	void AdvanceTimer();

	UFUNCTION(BlueprintNativeEvent)
	void CountdownHasFinished();
	virtual void CountdownHasFinished_Implementation();

	FTimerHandle CountdownTimerHandle;
};

file:Countdown.cpp

#include "Components/TextRenderComponent.h"
#include "Countdown.h"

// Sets default values
ACountdown::ACountdown()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;
	CountdownText = CreateDefaultSubobject<UTextRenderComponent>(TEXT("CountdownNumber"));
	CountdownText->SetHorizontalAlignment(EHTA_Center);
	CountdownText->SetWorldSize(150.f);
	RootComponent = CountdownText;

	CountdownTime = 3;

}

// Called when the game starts or when spawned
void ACountdown::BeginPlay()
{
	Super::BeginPlay();

	UpdateTimerDisplay();
	GetWorldTimerManager().SetTimer(CountdownTimerHandle, this, &ACountdown::AdvanceTimer, 1.0f, true);
	
}

// Called every frame
void ACountdown::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

void ACountdown::UpdateTimerDisplay()
{
  //  CountdownText->SetText(FString::FromInt(FMath::Max(CountdownTime, 0)));
  CountdownText->SetText(FText::FromString(FString::FromInt(FMath::Max(CountdownTime, 0))));
}

void ACountdown::AdvanceTimer()
{
  --CountdownTime;
  UpdateTimerDisplay();
  if (CountdownTime < 1)
    {
      GetWorldTimerManager().ClearTimer(CountdownTimerHandle);
      CountdownHasFinished();
    }
}
void ACountdown::CountdownHasFinished_Implementation()
{
  //CountdownText->SetText(TEXT("GO!!"));
  CountdownText->SetText(FText::FromString("GO!!"));
}

memo:
UFUNCTION(BlueprintNativeEvent)と宣言することで、BlueprintからCountdownHasFinishedを呼び出すことが可能になっている。

サンプルを見ずにC++でコーディングできる日が来るのかどうかは分からないけど、プログラミングすることでパーツの動きを制御できるのは面白くてワクワクする。

docs.unrealengine.com