Negative Value when Squaring/Absolute Value

Hi all, I am trying to write some code for my AI to attack the player when it gets close enough. I have attempted several methods, but they all are giving some strange return values/interacting oddly with my conditional. Apologizes in advance as I am still pretty new to UE4.

Player/Enemy Variable Declarations:

AAI_Bot* MyCharacter = Cast<AAI_Bot>(GetPawn());
ADemoProjectMainCharacter* Player = Cast<ADemoProjectMainCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));

Method 1: Subtracting enemy vector position from player, getting the size and then taking the absolute value of that result.

attackRange = FMath::Abs((MyCharacter->GetActorLocation() - Player->GetActorLocation()).Size());

Method 2: Using FVector:: DistSquared

attackRange = FVector::DistSquared(MyCharacter->GetActorLocation(), Player->GetActorLocation());

Method 3: Getting a reference to the pawn being controlled and using GetDistanceTo()

attackRange = GetPawn()->GetDistanceTo(Player);

All three methods are sometimes returning negative values and occasionally with step into the following conditional resulting in strange statements such in my log such as “567890302 <= 100”.

if (attackRange < 100.0f)
UE_LOG(LogTemp, Warning, TEXT("%d <= 100"), attackRange);

It’s impossible for a vectors’ size to be zero, so the abs is superfluous. You can also do FVector::Dist() to get the same result.

If you want to use DistSquared, then you also need to square the attack range to compare against too. Squared is a faster distance calculation but you have to square all the values you compare to as well. Your if statement would become AttackRange <= (100 * 100)

Make sure you are running the game through visual studio in DebugGame Editor mode.

Development Editor is useless for debugging because you will not be able to step through the code properly, since the code will be optimized and moved around.

Interesting, it seems the result was correct (non-negative number) but my log statement was giving something completely different and making me question what was happening. Now I know not to trust the development editor. Thanks for the help!

The issue is your log statement. %d is for integers, you are passing in a float. So under the hood, your float is being read as an integer which is why you get negative whatever value.

printf - C++ Reference See the Format section.