Slightly different solution to the challenge

Just a different approach that, as far as I can tell, works as well as the one used in the lecture. The relevant bits:

UTankAimingComponent::UTankAimingComponent()
{
	PrimaryComponentTick.bCanEverTick = true;

	FiringStatus = EFiringStatus::Reloading;
	LaunchSpeed = 5000.f;
	ReloadTimeInSeconds = 3.f;
}

void UTankAimingComponent::BeginPlay()
{
	Super::BeginPlay();

	LastTimeFired = FPlatformTime::Seconds();
}

void UTankAimingComponent::TickComponent(float DeltaTime, enum ELevelTick TickType,
	FActorComponentTickFunction *ThisTickFunction)
{
	if ((FPlatformTime::Seconds() - LastTimeFired) <= ReloadTimeInSeconds)
	{ FiringStatus = EFiringStatus::Reloading; }
}

void UTankAimingComponent::MoveBarrelTowards(FVector AimDirection)
{
	if (!ensure(Barrel && Turret))
	{ return; }

	auto BarrelRotator = Barrel->GetForwardVector().Rotation();
	auto AimRotator = AimDirection.Rotation();
	auto DeltaRotator = AimRotator - BarrelRotator;

	if (DeltaRotator.IsNearlyZero(0.03f))
	{
		FiringStatus = EFiringStatus::Locked;

		return;
	}
	else
	{
		FiringStatus = EFiringStatus::Aiming;

		Barrel->Elevate(DeltaRotator.Pitch);
		Turret->Rotate(DeltaRotator.Yaw);
	}
}

On further testing (I wasn’t playing with AI tanks – oops), I found the code doesn’t work as expected. The AI tanks fire continuously.

My fix was to create a private method on UTankAimingComponent, bool IsFiringReady() const, and use it as a guard in the Fire() method. Parts changed:

void UTankAimingComponent::TickComponent(float DeltaTime, enum ELevelTick TickType,
	FActorComponentTickFunction *ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	if (!IsFiringReady()) // ← here
	{ FiringStatus = EFiringStatus::Reloading; }
}

void UTankAimingComponent::Fire()
    {
    	if (!ensure(Barrel))
    	{ return; }

	if (!IsFiringReady()) // ← here
	{
		return;
	}
	else
	{
		// omitted
	}
}

Method added:

bool UTankAimingComponent::IsFiringReady() const
{
	auto bReady = (FPlatformTime::Seconds() - LastTimeFired) > ReloadTimeInSeconds;

	return bReady;
}

Privacy & Terms