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] from @. (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!
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]
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.
What about pure blueprint scripting? I have tried this method but it doesn’t work
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.
Thank you, C++ code works great !!!