Help with 2d side scrolling racing game positions

Hello, I’m making a side scrolling(from the left to the right) racing game and I’m trying to calculate the player’s position. But it’s really messed up, It sometimes only calculates for 1 car and other times for both. This is the code I’ve got so far

if (!hasFinishedRace)
         {
             foreach (Transform t in aiCars)
             {
                 print(t.name);
                 if (player.position.x > t.transform.position.x)
                 {
                     if (playerPosition > 1)
                     {
                         playerPosition--;
                     }
                 }
                 else
                 {
                     if (playerPosition < aiCars.Length + 1)
                     {
                         playerPosition++;
                     }
                 }
             }
             if (playerPosition == 1)
             {
                 positionText.text = playerPosition.ToString() + "st";
             }
             else if (playerPosition == 2)
             {
                 positionText.text = playerPosition.ToString() + "nd";
             }
             else if (playerPosition == 3)
             {
                 positionText.text = playerPosition.ToString() + "rd";
             }
             if (playerPosition != 3 && playerPosition != 2 && playerPosition != 1)
             {
                 positionText.text = playerPosition.ToString() + "th";
             }
         }
List<Transform> positions = aiCars.OrderBy(t => t.transform.position.x).ToList();
int playerPosition = positions.IndexOf(player);
string playerPositionText = (playerPosition + 1).ToString() + " " + (new string[] { "st", "nd", "rd", "th" })[Mathf.Min(playerPosition, 3)];

If your race is from right to left, replace OrderBy with OrderByDescending
The above code uses LINQ, so remember to add “using System.Linq”
Also, consider creating the string array with position suffixes in Awake() for performance.

Ok, thanks I will try it tomorrow :slight_smile:

Hello, it’s not working when I put your code in my for each loop it says t is already defined, so what is t and where do I get it from? And I get an array index is out of range for this line string playerPositionText = (playerPosition + 1).ToString() + " " + (new string[] { "st", "nd", "rd", "th" })[Mathf.Min(playerPosition, 3)];

Please help :slight_smile:

Never mind I was being a noob and a derp, I got it to work now. Thanks :slight_smile: