Hey guys,
This topic has been driving me up the walls and has shown me that I really don’t quite understand how arrays, lists, etc. work. I’ve already been trying to google for WEEKS (!!) now in order to find out how to do this kinda stuff properly, but this challenge has been way over my head so far.
So, here’s the design: I have a racing game and I want to always track the players positions. Every car has 3 variables:
lap = The lap the player is on
checkpoint = The number of checkpoints the player has passed
distanceToCheckpoint = The distance to the next checkpoint.
In terms of logic, I’m trying to sort it all in this order: Lap → Checkpoint → Distance.
So first I have to check over the laps the cars are on.
But if they’re on the same lap, I have to check which checkpoints they’re on.
But if they’re on the same checkpoint, I have to check which car is the closest to the next checkpoint.
I’ve been checking Unity Answers, the Unity Forums and some other places and since Javascript now supports Lists, I think most people suggest that lists should be used for something like that.
My issue is that this is really goddamn complicated, since I constantly have to Compare the variables within the arrays / lists between 4+ cars and then figure out who’s 1st, who’s 2nd, who’s 3rd, etc.
I found out that I can use a Compare Function like this:
function CompareCheckpoints(carP1: GameObject, carP2: GameObject): int
{
var scriptA = carP1.GetComponent(carSettings);
var scriptB = carP2.GetComponent(carSettings);
if (scriptA.checkpoint > scriptB.checkpoint) return -1;
if (scriptA.checkpoint < scriptB.checkpoint) return 1;
return 0;
}
…in order to find out which car is in the first place based on its checkpoint var. Now, this works nicely for 2 cars, but I’d have to do a whole lot of > and < in order to find out the differences between multiple cars.
So I kinda think I know how this could be done in a very, very complicated way, but I’m hoping someone here already coded something like this and could give me a hint on how to go about it in terms of logic / code, preferably in Javascript