Battery Collector #9 – Extending the Character Class

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

Extending the Character Class

We are going to work on the collection code. One is in the Character class and one in the Pickup.

Pickup Collection Code

In the Pickup.h, we declare a public function WasCollected:

/** Function to call when the pickup is collected */
 UFUNCTION(BlueprintNativeEvent)
 void WasCollected();
 virtual void WasCollected_Implementation();

The function is BlueprintNativeEvent, so it can be overridden by a blueprint and has a native implementation.

In the base Pickup.cpp source file, we define the function:

void APickup::WasCollected_Implementation()
{
 // Log a debug message
 FString PickupDebugString = GetName();
 UE_LOG(LogClass, Log, TEXT("You have collected %s"), *PickupDebugString);
}

It just logs text.
In the BatteryPickup.h header file, we declare it also:

/** Override the WasCollected function - use Implementation because it's a Blueprint Native Event */
 void WasCollected_Implementation() override;

And in the BatteryPickup.cpp source file, we define the function:

void ABatteryPickup::WasCollected_Implementation()
{
// Use the base pickup behavior
Super::WasCollected_Implementation();
// Destroy the battery
Destroy();
}

We don’t destroy in the base pickup, in case we want to do something else with it when it is picked up.

Character Collection Code

We open the BatteryCollectorCharacter.h header file. This file has been generated by the 3rd Person Template. We declare a new sphere component:

/** Collection sphere */
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
 class USphereComponent* CollectionSphere;

And at the end, we add the accessor function:

/** Returns CollectionSphere subobject **/
 FORCEINLINE class USphereComponent* GetCollectionSphere() const { return CollectionSphere; }

In the BatteryCollectorCharacter.cpp source file, we create the sphere in the constructor:

// Create the collection sphere
 CollectionSphere = CreateDefaultSubobject<USphereComponent>(TEXT("CollectionSphere"));
 CollectionSphere->AttachTo(RootComponent);
 CollectionSphere->SetSphereRadius(200.0f);

Next Step

In the next step, we will collect pickups

About

Gamer

Tagged with:

Leave a Reply