How do I target a specific enemy?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By da_dev

So, I have a KinematicBody2D as a player’s soldier, and another one as an enemy. I have all nodes of every single friendly soldier and every single enemy stored in two global arrays.
I want to have a soldier, which upon entering a “detection radius” would start firing at the enemy sprite. I tried this:

#	Spotting an enemy and firing
for i in gv.enemies: #gv is global variables
	var enemy = i
	if (position.x - i.position.x) * (position.x - i.position.x) + (position.y - i.position.y) * (position.y - i.position.y) < detection_radius * detection_radius: #if soldier is in range of any of the enemies
		while (position.x - enemy.position.x) * (position.x - enemy.position.x) + (position.y - enemy.position.y) * (position.y - enemy.position.y) < detection_radius * detection_radius: #if soldier is still in range of the enemy
			var enemy_angle = enemy.position - self.position 
			rotation = enemy_angle.angle() + deg2rad(90)
			print("if")
			if (bullets > 0 && canFire):
				auto_fire()
	else:
		rotation = trans.angle() + deg2rad(90)#
		print("else")

Surprisingly, when I run this code, game lags at the start and doesn’t begin. I’ve noticed that’s something with the “while” block.

Anybody has idea how to solve this?

There are many, many things wrong with this code and your approach. I highly suggest reading through the Godot docs, especially the “Step by step” section, to learn how Godot works. Do the tutorial game in that section.

Some suggestions:

  1. Area2D should be used to detect objects entering/exiting
  2. while loops should be avoided as they block game processing. Your code needs to run once per frame, don’t block the game loop.
  3. Your distance calculations could be much simpler. Read up on how vectors work, and see Vector2.length(): Vector math — Godot Engine (latest) documentation in English

kidscancode | 2019-06-12 16:01

Thank you! I really have to be more patient when reading Godot docs (I really want to create fancy stuff before I learn the basics)

da_dev | 2019-06-12 16:59