Topic was automatically imported from the old Question2Answer platform.
Asked By
master8829
I am creating a 2D game
I am not able to find the closest enemy to the player I’m using
as well as my code to find the closest enemy only updates twice then stops working
as well as it requires me to be so close to the enemy
script:
func find_closest_enemy() -> Object:
var all_enemy = get_tree().get_nodes_in_group("enemy")
for enemy in all_enemy:
var gun2enemy_distance = position.distance_to(enemy.position)
if gun2enemy_distance < closestDistance:
closestDistance = gun2enemy_distance
closestEnemy = enemy
return closestEnemy
closestEnemy = null
func _ready():
closestEnemy = find_closest_enemy()
func _process(delta):
var newClosestEnemy = find_closest_enemy()
newClosestEnemy = closestEnemy
print(closestEnemy)
This will only find the closest because the method find_closest_enemy always compares to the previous closestEnemy. So at some point, a distance will only be closer if closer than the previous, and then closer still until the distance is tiny.
You probably want to start with a large distance rather than the previously closest distance. A small change here could be to make closestDistance local to the method and some large value that will always encompass all enemies (or change the logic to always take the first enemy)
how can I make clesestDistance local without effecting the logic ?
master8829 | 2023-06-25 20:01
Set closest to a large value when the method begins.
Do you understand why it is failing currently? First time, let’s say it finds an enemy at a distance of 10 so this is now closest. Next time it finds an enemy at 5; great, closest is now 5.
Another pass, and the closest is an enemy at 6 but because closest is 5 (whether there’s an enemy here or not), it ignores 6.
So you need to ‘reset’ closest each time. Good luck!
spaceyjase | 2023-06-25 21:35
The code now updates but i have to be really close to an enemy for it to register as the closest . eventhough i reset closestdistance everytime the function runs
func find_closest_enemy() -> Object:
var all_enemy = get_tree().get_nodes_in_group("enemy")
for enemy in all_enemy:
var gun2enemy_distance = position.distance_to(enemy.position)
if gun2enemy_distance < closestDistance:
closestDistance = gun2enemy_distance
closestEnemy = enemy
return closestEnemy
closestDistance = 1000
func _ready():
closestEnemy = find_closest_enemy()
func _process(delta):
var newClosestEnemy = find_closest_enemy()
newClosestEnemy = closestEnemy
master8829 | 2023-06-27 11:48
I’m surprised that even compiles but if it does, you should reset the value at the start of the method, not after the return (where it is unreachable).
Almost there!
spaceyjase | 2023-06-27 12:39
Its working now ,thank you very much for your help.
when I reseted the value correctly it worked