Sphere traces, get furthest left of player, then add to array from left to right.

Hello Unreal Forums.

I would like to know, how I can get the furthest actor to the left from a sphere trace, add that to the array first, and then add each remaining actor from furthest left to furthest right.

Example Picture:

So actor 1 would be first added to the array, then 2 then 3 then 4.

I know how to get all the actors to the left of the player using the sphere trace to get the actors, then a line trace with a dot product and the same for the right. What I don’t know, is how to add them to an array in order from left to right.

In c++ it would be something like:

TArray<AActor*> FoundActors = /* result of your sphere overlap */;
AActor* Player = /* player ptr */;

// assuming you want to sort by angle. If you need to sort by "X" relatively to Fwd - change comparator accordingly
FoundActors.Sort([Player](AActor* A, AActor* B)->bool{
   FVector Fwd = Player->GetActorForwardVector();
   float AngleA = UMyUtils::GetSignedAngleBetweenVectors(
			A->GetActorLocation() - Player->GetActorLocation(), Fwd);
   float AngleB = UMyUtils::GetSignedAngleBetweenVectors(
			B->GetActorLocation() - Player->GetActorLocation(), Fwd);
   return AngleA < AngleB; //may reverse sign if order is wrong
});

//note that while we passing in 3d vectors we treat them as 2d projected on z=0
float UMyUtils::GetSignedAngleBetweenVectors(FVector V1, FVector V2)
{
	//actually don't remember the math behind it, but it should work
	return UKismetMathLibrary::DegAcos(UKismetMathLibrary::Vector_CosineAngle2D(V1, V2)) * FMath::Sign(FVector::CrossProduct(V1, V2).Z);
}

and expose it to bp.

If you need a bp-only solution, then I don’t think BP supports sorting with custom comparator (i may be wrong though, this doesn’t crossed my mind even once), so there is no sane way besides exposing sort with custom comparator or writing your own sort in bp (don’t do it, it’s weird)

I have no idea how to make this into a function for use with unreal engine, will have to do some research