Using FTimerManager instead

So in this thread @GamedevCala linked the docs page for FTimerHandler as a suggested alternative for using GetWorldTimeSeconds and FPlatformTime. I think it would be nice to switch to this instead of the two aforementioned methods. Here is the replacement code needed

in TankAimingComponent.h add FTimerHandle ReloadTimerHandle; and then in the following changes in the .cpp

void UTankAimingComponent::BeginPlay()
{
    //delegate function to be called when timer finishes
    FTimerDelegate 
    //bind a lambda function to the delegate
    Delegate.BindLambda([=] { FiringState = EFiringState::Locked; });
    GetWorld()->GetTimerManager().SetTimer(ReloadTimerHandle, Delegate, ReloadTimeInSeconds, false);
 }

void UTankAimingComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
	bool isReloading = GetWorld()->GetTimerManager().IsTimerActive(ReloadTimerHandle);
	if (!isReloading)
	{
		if (IsBarrelMoving())
		{
			FiringState = EFiringState::Aiming;
		}
		else
		{
			FiringState = EFiringState::Locked;
		}
	}
}
void UTankAimingComponent::Fire()
{
	bool isReloading = GetWorld()->GetTimerManager().IsTimerActive(ReloadTimerHandle);
	if (!isReloading)
	{
		FiringState = EFiringState::Reloading;
		// Spawn a projectile at the socket location on the barrel
		if (!ensure(Barrel)) { return; }
		if (!ensure(ProjectileBlueprint)) { return; }
		auto Projectile = GetWorld()->SpawnActor<AProjectile>(
			ProjectileBlueprint,
			Barrel->GetSocketLocation(FName("Projectile")),
			Barrel->GetSocketRotation(FName("Projectile"))
			);

		Projectile->LaunchProjectile(LaunchSpeed);
		FTimerDelegate Delegate;
		Delegate.BindLambda([=] { FiringState = EFiringState::Locked; });
		GetWorld()->GetTimerManager().SetTimer(ReloadTimerHandle, Delegate, ReloadTimeInSeconds, false);
	}
}

Edit: wow, thats a lot of wasted space on the right making the code box really small :confused:. Also I coded most of this before I did the IsBarrelMoving part, so realistically you could use the SetTimer which doesn’t take a delegate since Locked should be set in the tick function so it’s not really needed, but I guess it’s useful knowing you can pass one in and sort of how to do so.

Just to let you know we will be using FTimerManager towards the end of the section, around lecture 93.

1 Like

Privacy & Terms