Comparing multiple values

Hello, I am trying to make a multiplayer racing game, where the player that is further away from the finish line gets more speed so that he could catch up. Each player calculates its own distance to the finish line, and then another script should compare all distances and change the speed of the player that is further away. I want the game to have 5 players max. In the script all the players are stored in a array. And I can get each of the players distances by accessing a function in the players Movement script. For example:

void Update()

{

Player0Dist = Players[0].GetComponent().FinishDist();

Player1Dist = Players[1].GetComponent().FinishDist();

}

Player0Dist and so on are a floats. Now I need to somehow compare these floats so that the player with the largest distance to the finish would get the biggest speed. So if Player4Dist distance is the largest his speed would be 5, if Player2Dist is second to largest his speed would be 4 and so on. I could just write a bunch of if statements but that would be very ugly :stuck_out_tongue: .I thought about putting all of these floats into a array and sorting it, but then how would I know which float represent which player. So it would be very helpful if someone could tell me a way to compare 5 floats and get the largest, second to largest, third to largest and so on while still knowing which float represent which player.

Based on what you said, do you really need the distances order? You could get distance max, min and get bonus on linear proportion to it. We will be using Mathf.InverseLerp

Example:

using System.Linq;

public class Player: MonoBehaviour
{
    public float Speed;
    public float Distance;
}

// elsewhere

const float BaseSpeed = 10; // Base car speed without bonus
const float Bonus = 5; // Max bonus from distance

float max = Players.Max(p => p.Distance);
float min = Players.Min(p => p.Distance);
Players.ForEach(p => p.Speed = BaseSpeed + (Bonus * Mathf.InverseLerp(min, max, p.Distance)));

ForEach is a List<> method. You can use a standard for in your array.

1 Like

You can also do it without LINQ. Which may be easier for a novice coder.

public class Player: MonoBehaviour
{
    public float speed;
    public float distance;
}

// elsewhere

float baseSpeed = 10; // Base car speed without bonus
float bonus = 5; // Max bonus from distance

float max = 0;
float min = Mathf.infinity;
foreach (Player player in players){
    if (player.distance > max) max = player.distance;
    if (player.distance < min) min = player.distance;
}
foreach (Player player in players){
    player.speed = baseSpeed + (bonus * Mathf.InverseLerp(min, max, p.Distance)))
}

If you simply want the order, you can put each player into an array. Then sort the array by player speed. You could do this by implementing IComparable on Player. Or by passing in a IComparer of your own. The second solution probably makes the most sense.