Distance check before the progress check

My solution to the challenge was to put the distance check before the progress check, because I thought: let’s first see if the enemy is in range and then find out which one is closet to the base.

Is there a difference that I’m overlooking or are both solutions fine?

This is my code:

func find_best_target() -> PathFollow3D:
	var best_target = null
	var best_progress = 0
	
	for enemy in enemy_path.get_children():
		if enemy is PathFollow3D:
			var distance = global_position.distance_to(enemy.global_position)
			if distance < turrent_range:
				if enemy.progress > best_progress:
					best_target = enemy
					best_progress = enemy.progress
	
	return best_target
1 Like

Nice work, Thanks for sharing Bever

Nice, saves some processing!

I went a different direction as well, to reduce the number of nested if-statements. And changed the function name since it actually returns a target.

func get_best_target() -> PathFollow3D:
	var best_target = null
	var best_progress = 0
	
	for enemy in enemy_path.get_children():
		if not enemy is PathFollow3D:
			continue
		
		if global_position.distance_to(enemy.global_position) > turret_range:
			continue
		
		if enemy.progress > best_progress:
			best_target = enemy
			best_progress = enemy.progress
	
	return best_target

The ‘continue’ here means ‘skip this item in the for-loop, go to the next one’.

4 Likes

cheers for sharing. both approaches will give you the same results in the end.
its soo nice to see the turrets actually doing their thing at this point in the course as well :slight_smile:

I did the following:

func find_best_target() -> PathFollow3D:
	var best_target = null
	var best_progress = 0
	for enemy in enemy_path.get_children():
		var distance = global_position.distance_to(enemy.global_position)
		if enemy is PathFollow3D and distance <= turret_range:
			if enemy.progress > best_progress:
				best_target = enemy
				best_progress = enemy.progress
	return best_target

Since I am not a genius at coding: Is there any major downside of this approach?

1 Like

In this case it’s mainly readability, but in other case having multiple nested if statements could impact performance

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms