Hi, I’m new to the Unreal Engine but I’m quite familiar with the C++ language.
I want to create a 3D game of life using a TMap of cubes. Here’s the code of the Main Actor:
// Fill out your copyright notice in the Description page of Project Settings.
#include "GameOfLife.h"
#include "MainDirector.h"
// Sets default values
AMainDirector::AMainDirector()
{
// 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;
Size.X = 16;
Size.Y = 16;
Size.Z = 16;
AnimationSpeed = 1.0f;
SetActorHiddenInGame(true);
}
// Called when the game starts or when spawned
void AMainDirector::BeginPlay()
{
Super::BeginPlay();
int x, y, z;
FVector origin = this->GetActorLocation();
for (x = 0; x < Size.X; x++)
{
for (y = 0; y < Size.Y; y++)
{
for (z = 0; z < Size.Z; z++)
{
FVector index(x, y, z);
_cells[index] = false;
AActor* cell = GWorld->SpawnActor(Cell->GetActorClass());
if (cell)
{
FVector location = origin + CubeSize * FVector(x, y, z);
cell->SetActorLocation(location);
cell->SetActorHiddenInGame(true);
_spawnedActors[index] = cell;
}
}
}
}
}
// Called every frame
void AMainDirector::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
static float currentTime = 0.0f;
currentTime += DeltaTime;
if (currentTime >= AnimationSpeed)
{
currentTime = 0.0f;
UpdateGrid();
}
}
bool AMainDirector::isAlive(FVector position) const
{
return _cells[position];
}
uint32 AMainDirector::GetAdjacentCellsAlive(FVector position) const
{
uint32 alive = 0;
const uint32 x0 = FMath::Clamp<float>(position.X - 1, 0, Size.X - 1);
const uint32 x1 = FMath::Clamp<float>(position.X + 1, 0, Size.X - 1);
const uint32 y0 = FMath::Clamp<float>(position.Y - 1, 0, Size.Y - 1);
const uint32 y1 = FMath::Clamp<float>(position.Y + 1, 0, Size.Y - 1);
const uint32 z0 = FMath::Clamp<float>(position.Z - 1, 0, Size.Z - 1);
const uint32 z1 = FMath::Clamp<float>(position.Z + 1, 0, Size.Z - 1);
uint32 x, y, z;
for (x = x0; x <= x1; x++)
for (y = y0; y <= y1; y++)
for (z = z0; z <= z1; z++)
alive += isAlive(FVector(x, y, z));
return alive;
}
void AMainDirector::UpdateGrid()
{
TMap<FVector, bool> newGrid = _cells;
uint32 alives;
for (auto& pair : newGrid)
{
alives = GetAdjacentCellsAlive(pair.Key);
if (pair.Value == true)
{
if (alives < 7 || alives > 10)
pair.Value = false;
}
else
{
if (alives >= 10 && alives <= 12)
pair.Value = true;
}
}
_cells = newGrid;
}
Now, whenever I try to run this code, Unreal crashes and shows an error report. I’d like to know of a debugging method on how to prevent this. Thanks for the reply and kudos to people finding the problem in this code (I assume it has to do with the TMaps).