How do I sort an array by distance?

Hello, I’m creating a third person shooter game and I want my companions to follow me in a V Formation. I have gotten the formation already but the function that I used to sort the companion array by distance is not working well. Because the formation is symmetrical, when the player continues to move in the same direction, the two companions beside it maintain the same distance from it, hence the function tends to resort the array and make the two companions swap sides.

I have tried sorting the array only once so that the index assigned to each actor is the same throughout but this is not the ideal result I was going for as it is a very inflexible and inefficient way.

I’m currently following this [blueprint][1] from @[][2]. (Thank you!)

How can I program the sorting array such that when two values are the same, the formation will still be consistent?

I am still new to UE4 and have been struggling for days for my project. Hope to hear from all of you soon. Thank you so much for your help!

221682-formation.png

Here we go. You are looking for a sort algorithm available in the TArray class, called Sort. [Click here to see more information about C++ Arrays in UE4][1]

You will need to create a Blueprint Function Library if you want to use it in Blueprints. First of all, go to UE, right click in any content folder and create a new C++ class derived from Blueprint Function Library.

I made mine and named it as StaticFunctions. When it is successfully created and compiled, go to your .h file and do this declaration:

Then go to your .cpp file, and create the definition:

Go to UE and click in Compile button beside the Play button. Once the code has compiled, all you need to do is call OrderByDistance in any blueprint you wish to use it.

2 Likes

What about pure blueprint scripting? I have tried this method but it doesn’t work :slight_smile:

If you want it to be BP only, this setup should work. If you want to order them from closest to farthest, change the Max of Float Array function for the Min version.

This didn’t work for me. But this did work: Tapa's Sort Array by distance posted by anonymous | blueprintUE | PasteBin For Unreal Engine 4

Thank you, C++ code works great !!!

Awesome function, it’s a shame it’s not a part of the engine code (should be in Gameplay Statics or sth).

Just one small remark - for optimization I’d advise using GetSquaredDistanceTo, as we don’t need absolute distances anywhere.