i++

プログラム系のメモ書きなど

Unreal Engine : Timeline を C++ コードで作成・実行する

手順

準備
  1. Timeline で使用する Curve を「Content Browser を右クリック」→「Miscellaneous」→「Curve」(もしくは「Float Curve」)で作成する
  2. 作成した Curve を右クリックして「Copy Reference」する
  3. C++ のコード上で ConstructorHelpers::FObjectFinder を使い、先ほど作成した Curve を取得する
  4. FTimeline オブジェクトを作成する
  5. FTimeline オブジェクトに追加する FOnTimeline* (FOnTimelineVector や FOnTimelineFloat など Curve の種類による)を作成する
  6. FOnTimeline* に、Timeline が更新される毎に呼び出す関数を設定する
  7. FTimeline に、Curve と FOnTimeline* を追加する

Timeline 完了時のイベントを追加する場合のために SetTimelineFinishedFunc などもあるので、適宜使用する。

実行
  1. FTimeLine の PlayFromStart 関数を呼ぶ
    • 途中から再生する場合は Play、逆再生する場合は Reverse など再生開始方法は任意
  2. Tick で FTimeline の IsPlaying() が真であれば、TickTimeline(DeltaTime) を呼ぶ
    • 更新頻度が低くて良い場合は Tick ではなく TickTimeline を呼ぶだけの関数を設定した Timer を作成したほうが負荷が軽くなって良いかも

サンプルコード

void MyActor::MyActor()
{
    // 他の初期化処理...

    // メンバー変数として FTimeline* MyTimeline を定義している
    MyTimeline = new FTimeline();
    MyTimeline->SetTimelineLength(1.0f);

    // 作成した Timeline の取得。Copy Reference でコピーしたテキストを TEXT の中に貼り付ける。
    // <> の中身は Curve の種類によって変更する。今回は Vector。 
    const ConstructorHelpers::FObjectFinder<UCurveVector> StepCurve(TEXT("CurveVector'/Game/Timeline/TimelineCurve.TimelineCurve'"));

    // Timeline 更新時に呼ばれる関数の設定。このクラスに定義している void TimelineStep(FVector v) を呼ぶ。
    FOnTimelineVector MyTimelineStepFunction;
    MyTimelineStepFunction.BindUFunction(this, "TimelineStep");
    MyTimeline->AddInterpVector(StepCurve.Object, MyTimelineStepFunction);

    // Timeline 終了時に呼ばれる関数の設定。このクラスに定義している void TimelineFinished(FVector v) を呼ぶ。
    FOnTimelineEvent MyTimelineFinishedFunc;
    MyTimelineFinishedFunc.BindUFunction(this, "TimelineFinished");
    MyTimeline->SetTimelineFinishedFunc(MyTimelineFinishedFunc);
}

void MyActor::BeginPlay()
{
    if (MyTimeline != nullptr) {
        MyTimeline->PlayFromStart();
    }
}

void MyActor::Tick( float DeltaTime )
{
    Super::Tick( DeltaTime );

    // Timeline 再生中であれば DeltaTime 進めて実行
    if (MyTimeline != nullptr && MyTimeline->IsPlaying())
    {
        MyTimeline->TickTimeline(DeltaTime);
    }
}

// TickTimeline 毎に、進んだ Time の合計と対応した Timeline から得られる値でこの関数が呼ばれる
// .h で定義する際に UFUNCTION() を付けておくこと
void MyActor::TimelineStep(FVector value)
{
    UE_LOG(LogTemp, Warning, TEXT("TimelineStep : (%.2f, %.2f, %.2f)"), value.X, value.Y, value.Z);
}

// Timeline 完了時に呼ばれる関数
// .h で定義する際に UFUNCTION() を付けておくこと
void MyActor::TimelineFinished()
{
    UE_LOG(LogTemp, Warning, TEXT("TimelineStep Finished"));
}

参考


Blueprint も良くできていると思いますが、メインは C++ で書いたほうが楽そうです。

Unreal Engine 4で極めるゲーム開発:サンプルデータと動画で学ぶUE4ゲーム制作プロジェクト

Unreal Engine 4で極めるゲーム開発:サンプルデータと動画で学ぶUE4ゲーム制作プロジェクト