Topic was automatically imported from the old Question2Answer platform.
Asked By
behelit
Up until now, I’ve been using Area2D to handle collisions with _on_Area2D_area_entered, as well as ray casting. Also, I understand how the enemy might get the player location to launch it’s own homing missile (there is only one player). However… How would you handle getting the enemy’s location, especially when there might be multiple enemies on the screen? The problem is melting my brain, could really use some help. No need for an exact solution, pseudo code and the appropriate functions would be extremely helpful! Preferably, I’d like to target the closest enemy who is in front of the player.
func get_closest_enemy():
var enemies = get_tree().get_nodes_in_group('Enemies')
if enemies.empty(): return null
var distances = []
for enemy in enemies:
var distance = player.global_position.distance_squared_to(enemy.global_position)
distances.append(distance)
var min_distance = distances.min()
var min_index = distances.find(min_distance)
var closest_enemy = enemies[min_index]
return closest_enemy
This sounds like it will work, thanks for the tip! Just needed to get my head in the right place.
behelit | 2019-07-12 02:30
Here’s an alternative version which doesn’t use Array:
func get_closest_enemy():
var enemies = get_tree().get_nodes_in_group('Enemies')
var closest_enemy = null
var min_distance = INF
for enemy in enemies:
var distance = player.global_position.distance_squared_to(enemy.global_position)
if distance < min_distance:
min_distance = distance
closest_enemy = enemy
return closest_enemy
Dlean Jeans | 2019-07-12 11:14
Actually, the first solution works beautifully, it’s exactly what I needed. Thank you for your help! I need to learn how arrays worked in Godot anyway. haha