I’m trying to spawn fish at a random position inside of the box that I have assigned as my fish manager. But my current issue is that if they collide with a random object other than themselves, they will spawn at 0,0,0 and a big explosion of fish happens every time if there are objects in the box that are in the way of the fish. How do I find the objects in the scene that I can then tell the fish “Hey, this position is taken, go and find a new one”? Any help would be appreciated! Thank you.
#include "FishManager.h"
#include "FishActor.h"
#include "Components/BoxComponent.h"
// Sets default values
AFishManager::AFishManager()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
Root = CreateDefaultSubobject<USceneComponent>("Root");
SetRootComponent(Root);
BoxComponent = CreateDefaultSubobject<UBoxComponent>("Box Collider");
BoxComponent->SetupAttachment(Root);
}
// Called when the game starts or when spawned
void AFishManager::BeginPlay()
{
Super::BeginPlay();
SpawnFish();
}
// Called every frame
void AFishManager::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
//Gets a random location in the box collider set in the world.
FVector AFishManager::GetRandomLocation() const
{
FVector BoxExtent = BoxComponent->GetScaledBoxExtent();
FVector BoxOrigin = BoxComponent->GetComponentLocation();
FBox Box(BoxOrigin - BoxExtent, BoxOrigin + BoxExtent);
FVector RandomPoint = FMath::RandPointInBox(Box);
return RandomPoint;
}
void AFishManager::SpawnFish()
{
FVector BoxExtent = BoxComponent->GetScaledBoxExtent();
FVector BoxOrigin = BoxComponent->GetComponentLocation();
for (int32 i = 0; i < FishAmount; i++)
{
FVector SpawnLocation = FMath::RandPointInBox(FBox(BoxOrigin - BoxExtent, BoxOrigin + BoxExtent));
// Check if the spawn location is too close to any existing fish
bool bTooClose = false;
for (AFishActor* Fish : FishList)
{
if (FVector::Dist(SpawnLocation, Fish->GetActorLocation()) < 20.f)
{
bTooClose = true;
break;
}
}
// If the spawn location is too close to any existing fish, re-spawn or adjust the location
if (bTooClose)
{
i--; // change this
continue;
}
// Spawn the fish
AFishActor* NewFish = GetWorld()->SpawnActor<AFishActor>(FishClass, SpawnLocation, FRotator::ZeroRotator);
NewFish->Fish.Size = 1; //Score
NewFish->Fish.FishType = FishType::Small; // Maybe score too?
NewFish->FishManager = this;
FishList.Add(NewFish);
}
}