+1 vote

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.

in Engine by (74 points)
edited by

1 Answer

+4 votes
Best answer

This semi-pseudo code should work:

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
by (4,165 points)
selected by

This sounds like it will work, thanks for the tip! Just needed to get my head in the right place.

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

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

Agreed this works awesome sauce!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.