Battery Collector #10 – Collecting Pickups

I am continuing the Battery Collector tutorial. This is the 10th video. Click here for the first part and here for the previous one.

Collecting Pickups

In the BatteryCollectorCharacter.h, I am declaring a CollectPickups function:

/** Called when we press a key to collect any pickups inside the CollectionSphere */
 UFUNCTION(BlueprintCallable, Category = "Pickups")
 void CollectPickups();

Then in the BatteryCollector .cpp file, I am including Pickup.h:

#include "Pickup.h"

Down at the bottom, I am defining the CollectPickups function:

void ABatteryCollectorCharacter::CollectPickups()
{
	// Get all overlapping Actors and store then in an array
	TArray<AActor*> CollectedActors;
	CollectionSphere->GetOverlappingActors(CollectedActors);

	// For each Actor we collected
	for (int32 iCollected = 0; iCollected < CollectedActors.Num(); ++iCollected)
	{
		// Cast the Actor to APickup
		APickup* const TestPickup = Cast(CollectedActors[iCollected]);
		
		// If the cast is successful and the pickup is valid and active
		if (TestPickup && !TestPickup->IsPendingKill() && TestPickup->IsActive())
		{
			// call the pickup's WasCollected function
			TestPickup->WasCollected();
			// Deactivate the pickup
			TestPickup->SetActive(false);
		}
	}
}

We now need a bind key to collect pickups. We do this in the SetupPlayerInputComponent:

InputComponent->BindAction("Collect", IE_Pressed, this, &ABatteryCollectorCharacter::CollectPickups);

Back to Unreal Editor, I am compiling the project and set the key pressed. This is done by opening the Project Settings and selecting Input.

InputSettings

To test it, I am opening the Output log (Window/Developer Tools menu):

OutputLog

When I hit play, I ca n collect the batteries by pressing “C” and see them disappearing while reading it in the log:

Collecting Batteries in log

Next Step

In the next step, I will add power to the game.

About

Gamer

Tagged with:

Leave a Reply