I am still learning C++ so naturally I am having trouble with pointers.
For hours, I was trying to find the trace that is closest to another object out of multiple traces. I used a simple for loop with a simple if thisTrace is closer than closestTrace, closestTrace = thisTrace logic.
I tried to save the deepest HitResult in a pointer but the results were confusing. Sometimes I got an empty (ImpactPoint = (0, 0, 0)) hit result, sometimes got a random (probably not random) hit result.
When I tried to save just the impact point in a FVector, it worked perfectly. So I am thinking my method of assigning an address to a pointer is wrong.
Can you help me?
First picture is the working code, second is the broken one. (cleaned them up a little to post here, I may have missed some syntax or something while cleaning)
Working code:
float DistanceToImpactPoint = INT32_MAX;
FVector DepestImpactPoint = FVector::ZeroVector;
for (int i = 0; i < numberOfContacts; i++)
{
FVector Start = Arrows[i]->GetComponentLocation();
FVector Direction = Arrows[i]->GetComponentTransform().GetUnitAxis(EAxis::X);
FHitResult HitResult(ForceInit);
bool bIsHit = Trace(HitResult, Start, Direction, 20.f);
if (bIsHit)
{
float Distance = FVector::DistSquared(Start, HitResult.ImpactPoint);
if (Distance < DistanceToImpactPoint)
{
DepestImpactPoint = HitResult.ImpactPoint;
DistanceToImpactPoint = Distance;
}
}
}
DrawDebugPoint(GetWorld(), DepestImpactPoint, 5.f, FColor::Red);
UE_LOG(LogTemp, Warning, TEXT("Dist: %f"), DistanceToImpactPoint);
Broken code:
FHitResult* DeepestHit = nullptr;
float DistanceToImpactPoint = INT32_MAX;
for (int i = 0; i < numberOfContacts; i++)
{
FVector Start = Arrows[i]->GetComponentLocation();
FVector Direction = Arrows[i]->GetComponentTransform().GetUnitAxis(EAxis::X);
FHitResult HitResult(ForceInit);
bool bIsHit = Trace(HitResult, Start, Direction, 20.f);
if (bIsHit)
{
float Distance = FVector::DistSquared(Start, HitResult.ImpactPoint);
if (DeepestHit == nullptr || Distance < DistanceToImpactPoint)
{
DeepestHit = &HitResult;
DistanceToImpactPoint = Distance;
}
}
}
if (DeepestHit != nullptr)
{
DrawDebugPoint(GetWorld(), DepestImpactPoint, 5.f, FColor::Red);
UE_LOG(LogTemp, Warning, TEXT("Dist: %f"), DistanceToImpactPoint);
}