Using TArray<> to hold Locations

I took a slightly different approach with a view to future expansions of more than two points for the platform to move between. Using a TArray to store the locations and when the locations have been reached increment an index to that array.

Also, I used IsNearlyZero() function from the FVector API to check whether the platform had arrived at its intended location. This could easily be changed to use the FVector length comparison.

MovingPlatform.h

...

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

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

private:
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Properties, meta = (AllowPrivateAccess = "true"))
	float Speed = 0.0f;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Properties, meta = (AllowPrivateAccess = "true", MakeEditWidget = "true"))
	FVector TargetLocation;

	bool MoveToPosition(FVector TargetLocation, float DeltaTime);

	TArray<FVector> AimLocations;
	int32 AimIndex;
};

MovingPlatfrom.cpp

...

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

	if (HasAuthority())
	{
		// Replicate this actor to the clients
		SetReplicates(true);
		SetReplicateMovement(true);
	}

	AimLocations.Add(GetActorLocation());
	AimLocations.Add(GetTransform().TransformPosition(TargetLocation));
	AimIndex = 1;
}

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

	if (HasAuthority()) // If Running on server
	{
		if (MoveToPosition(AimLocations[AimIndex], DeltaTime))
		{
			UE_LOG(LogTemp, Warning, TEXT("AimLocation achieved!"));

			AimIndex++;
			if (AimIndex >= AimLocations.Num())
			{
				AimIndex = 0;
			}
		}
	}
}

bool AMovingPlatform::MoveToPosition(FVector Location, float DeltaTime)
{
	FVector PlatformLocation = GetActorLocation();
	if ((PlatformLocation - Location).IsNearlyZero(5.0f))
	{
		return true;
	}
	else
	{
		FVector DirectionOffset = (Location - PlatformLocation).GetSafeNormal() * Speed * DeltaTime;
		SetActorLocation(PlatformLocation + DirectionOffset);
		return false;
	}
}
2 Likes

This was a genius idea. Great job :+1:

I was thinking about this the other day and just wondering if if the best way would be to use a bounce or cycle approach. Bounce as in 1-2-3-2-1 or cycle as 1-2-3-1. I figure adding a boolean to toggle on bounce so you can get the best of both worlds.

Thanks for sharing this.

Privacy & Terms