What is the best solution for counting player position in a racing game?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Bishop
:warning: Old Version Published before Godot 3 was released.

For example, I have two NPC cars + player car , how can I best count player/car order?

  1. throughout the race( on the track )…more complex
  2. only at the finish line…easier
    …solution number two would be sufficient for me.
    Thanks for help
:bust_in_silhouette: Reply From: Zylann

If solution 2 is good for you, why don’t you just do it? ^^

Solution 1 requires that you know where the car is in the road line between start and finish. A way to achieve it is to project the car’s position on the curve describing the road, and calculate the distance of this point along the curve so that you can compare two car’s advancements on the track. The rest is math :wink:

If you don’t need good precision you can cheat using checkpoints (see comments below)

Thanks Zylann,
I go for solution 2…but how the finish line get to know order of a cars…groups or object ID or something else ?..it would be better to show me more on the example script…if that’s possible?..I’m learning GDscript yet :-)…i don’t want it only for myself but for many beginners too…this is very useful because it’s the basis for a racing games.

…I have done laps counting on the finish line (area 2D trigger)
so…player car add to group ‘player’ and NPC cars add groups ‘car1’ and ‘car2’ and
triggering groups?

Bishop | 2017-06-08 16:09

Knowing player order from only the finish line requires that you store two things when they cross the line:

  1. The last time at which the player crossed the finish line
  2. The number of laps the player achieved

Then you can tell if a player is beyond another by doing the following test:

if player_a.lap_count == player_b.lap_count:
	# Players are in the same lap but one was late
	if player_a.lap_time > player_b.lap_time:
		# Player A is first
		# Player B is first
		# Note: if a car takes the lead over another during the same lap,
		# this code won't detect it, which is why solution 1 would be better.
elif player_a.lap_count > player_b.lap_count:
	# Player A is first
	# Player B is first

And then if you need the order as a list, then get all layers as an array, and use the sort_custom function using the code above.

It’s not very accurate for a racing game though. You could even this out by adding checkpoints maybe (or many many invisible checkpoints), but the most accurate solution would be 1.

You can alternatively use the travelled distance since last lap/checkpoint instead of lap_time, which would be more accurate but still biased because not based on the road curve.

Zylann | 2017-06-08 17:28

Thank you very much Zylann,
for example script and solution directions.

Bishop | 2017-06-08 20:13