I am continuing the Battery Collector in C++ tutorial from Unreal Engine. This is the 8th video.
This time we will define When to Spawn.
Setting Timers for Spawning
In the SpawnVolume.h header file, we add 3 protected variables: a spawn timer, a minimum spawn delay and a maximum spawn delay.
FTimerHandle SpawnTimer;
/** Minimum spawn delay */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spawning") float SpawnDelayRangeLow;
/** Maximum spawn delay */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spawning") float SpawnDelayRangeHigh;
In the private section, we add the spawn delay variable. It is private, so it can’t be modified by other classes.
/** The current spawn delay */ float SpawnDelay;
In the source file (SpawnVolume.cpp), we set default values for the spawn delay ranges in the constructor:
// Set the spawn delay range SpawnDelayRangeLow = 1.0f; SpawnDelayRangeHigh = 4.5f;
We modify the BeginPlay function, to start a timer:
// Called when the game starts or when spawned void ASpawnVolume::BeginPlay() { Super::BeginPlay(); SpawnDelay = FMath::FRandRange(SpawnDelayRangeLow, SpawnDelayRangeHigh); GetWorldTimerManager().SetTimer(SpawnTimer, this, &ASpawnVolume::SpawnPickup, SpawnDelay, false); }
We modify also the SpawnPickup function, to restart the timer at the end of the spawning:
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(WhatToSpawn, SpawnLocation, SpawnRotation); SpawnDelay = FMath::FRandRange(SpawnDelayRangeLow, SpawnDelayRangeHigh); GetWorldTimerManager().SetTimer(SpawnTimer, this, &ASpawnVolume::SpawnPickup, SpawnDelay, false); } } }
Back to Unreal Engine Editor, we compile and add a Spawn Volume in the level. We increase its size by 2.25, set the “What to Spawn” as Pickup_BP and the range for the delay between 2 and 6 seconds.
We add another Spawn Volume, increase its Y value by 8.75 and set set the “What to Spawn” as Battery_BP and the range for the delay between 0.5 and 2 seconds. Then we hit play and can see the different pickups spawned:
Next Step
In the next step, we will extend the Character class.
Leave a Reply