I am continuing the Battery Collector in C++ tutorial from Unreal Engine. This is the 7th video.
Defining What to Spawn
In the SpawnVolume.h header file, we declare a protected variable “WhatToSpawn”:
protected: /** The pickup to spawn */ UPROPERTY(EditAnywhere, Category = "Spawning") TSubclassOf<class APickup> WhatToSpawn;
We also declare a private function:
/** Handle spawning a new pickup */ void SpawnPickup();
In the SpawnVolume.cpp source file, we define that SpawnPickup behavior:
void ASpawnVolume::SpawnPickup() { // If we have set something to spawn: if (WhatToSpawn != NULL) { // Check for a valid World: UWorld* const World = GetWorld(); if (World) { // Set the spawn parameters FActorSpawnParameters SpawnParams; SpawnParams.Owner = this; SpawnParams.Instigator = Instigator; // Get a random location to spawn at FVector SpawnLocation = GetRandomPointInVolume(); // Get a random rotation for the spawned item FRotator SpawnRotation; SpawnRotation.Yaw = FMath::FRand() * 360.0f; SpawnRotation.Pitch = FMath::FRand() * 360.0f; SpawnRotation.Roll = FMath::FRand() * 360.0f; // Spawn the pickup APickup* const SpawnedPickup = World->SpawnActor<APickup>(WhatToSpawn, SpawnLocation, SpawnRotation); } } }
In order to use the Pickup functions, I need to include “Pickup.h” in this source file.
Someone in the comment section of the video says that there is also a util function in the Kismet library called UKismetMathLibrary::RandomRotator(bool bRoll = false) which does exactly the steps provided for getting a random rotation value.
Next Step
In the next step, we will define when to spawn.
Leave a Reply