头文件代码:
UCLASS()
class YOURGAME_API AYourClass: public AActor {
protected:
UPROPERTY()
UTimelineComponent* MyTimeline;
UPROPERTY()
UCurveFloat* FloatCurve;
UFUNCTION()
void TimelineCallback(float val);
UFUNCTION()
void TimelineFinishedCallback();
void PlayTimeline();
UPROPERTY()
TEnumAsByte<ETimelineDirection::Type> TimelineDirection;
public:
AYourClass();
};
cpp代码:
AYourClass::AYourClass()
{
static ConstructorHelpers::FObjectFinder<UCurveFloat> Curve(TEXT("/Game/Curves/C_MyCurve"));
check(Curve.Succeeded());
FloatCurve = Curve.Object;
}
void AYourClass::BeginPlay()
{
FOnTimelineFloat onTimelineCallback;
FOnTimelineEventStatic onTimelineFinishedCallback;
Super::BeginPlay();
if (FloatCurve != NULL)
{
MyTimeline = NewObject<UTimelineComponent>(this, FName("TimelineAnimation"));
MyTimeline->CreationMethod = EComponentCreationMethod::UserConstructionScript; // Indicate it comes from a blueprint so it gets cleared when we rerun construction scripts
this->BlueprintCreatedComponents.Add(MyTimeline); // Add to array so it gets saved
MyTimeline->SetNetAddressable(); // This component has a stable name that can be referenced for replication
MyTimeline->SetPropertySetObject(this); // Set which object the timeline should drive properties on
MyTimeline->SetDirectionPropertyName(FName("TimelineDirection"));
MyTimeline->SetLooping(false);
MyTimeline->SetTimelineLength(5.0f);
MyTimeline->SetTimelineLengthMode(ETimelineLengthMode::TL_LastKeyFrame);
MyTimeline->SetPlaybackPosition(0.0f, false);
//Add the float curve to the timeline and connect it to your timelines's interpolation function
onTimelineCallback.BindUFunction(this, FName{ TEXT("TimelineCallback") });
onTimelineFinishedCallback.BindUFunction(this, FName{ TEXT("TimelineFinishedCallback") });
MyTimeline->AddInterpFloat(FloatCurve, onTimelineCallback);
MyTimeline->SetTimelineFinishedFunc(onTimelineFinishedCallback);
MyTimeline->RegisterComponent();
}
}
void AYourClass::Tick(float deltaTime)
{
Super::Tick(deltaTime);
if (MyTimeline != NULL)
{
MyTimeline->TickComponent(deltaTime, ELevelTick::LEVELTICK_TimeOnly, NULL);
}
}
void AYourClass::TimelineCallback(float interpolatedVal)
{
// This function is called for every tick in the timeline.
}
void AYourClass::TimelineFinishedCallback()
{
// This function is called when the timeline finishes playing.
}
void AYourClass::PlayTimeline()
{
if (MyTimeline != NULL)
{
MyTimeline->PlayFromStart();
}
}