It is travel between two location at the given time-span

#pragma once

#include "Interact.h"

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MySlider.generated.h"

UCLASS()
class SHADOWSINTHELIGHT_API AMySlider : public AActor, public IInteract
{
	GENERATED_BODY()

public:
	AMySlider();
	virtual void Tick(float DeltaTime) override;
	FSInteract Interact_Implementation(UPrimitiveComponent* comp, const FString& str) override;

protected:
	virtual void BeginPlay() override;
	

	UPROPERTY()
	class USceneComponent* Root{};

	UPROPERTY(EditAnywhere, Category = "_Slider")
	class UStaticMeshComponent* sliderComp{};


	UPROPERTY(EditAnywhere, Category = "_Slider")
	FVector offset{ 0,0,100 };

	FVector source;
	FVector destination;

	UPROPERTY(EditAnywhere, Category = "_Slider")
	float duration = 2;
	float mytime{};

};
// There are two different position in space: the source and the destination 
// The goal is go the destination in given time-span(duration)
// 
// In the BeginPlay() function we initialize default variable and disable tick function. 
// We disable tick func. Because we don't need it unless the character enter interaction with this actor
// 
// When an another actor triger the interact interface We swap the source and the destination
// And we active the tick function if it is disabled. 
// 
// In the tick function we calculate the position by Lerp func. 
// When we arrived to the destination tick was disabled for incerease performance

#include "MySlider.h"

// Sets default values
AMySlider::AMySlider(){
	PrimaryActorTick.bCanEverTick = true;

	Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
	RootComponent = Root;

	sliderComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SliderComp"));
	sliderComp->SetupAttachment(Root);

}

// Open Close mechanism 
FSInteract AMySlider::Interact_Implementation(UPrimitiveComponent* comp, const FString& str){
	if (mytime > 0.01) mytime = duration - mytime; // swap the duration for non-finished movement 

	Swap(source, destination); // change the source and destination 
	this->SetActorTickEnabled(true);  

	return FSInteract();
}

void AMySlider::BeginPlay(){
	Super::BeginPlay();
	this->SetActorTickEnabled(false);

	source = GetActorLocation();
	destination = source + offset;	
	Swap(source, destination);
}

void AMySlider::Tick(float DeltaTime){
	Super::Tick(DeltaTime);
	mytime += DeltaTime;

	// Lerp func -> return (T)(A + Alpha * (B-A));
	FVector loc = FMath::Lerp(source, destination, mytime/duration);
	SetActorLocation(loc);

	if (mytime >= duration) {
		this->SetActorTickEnabled(false);
		mytime = 0;
	}


}


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *