Get the closest enemy / instance , look_at ?

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

I need the get closest enemy position that stored insade of array, so that gun can look at it.

this code on the gun node :

var shoot_distance:float = 30
var close_enemy = []

func _physics_process(delta):
	var all_enemy = get_tree().get_nodes_in_group("enemy")
	for enemy in all_enemy:
		var gun2enemy_distance = translation.distance_to(enemy.translation)
		if gun2enemy_distance < shoot_distance:
			close_enemy.append(gun2enemy_distance)
			look_at(enemy.translation,Vector3.UP) ## this line do not work.

when distance between enemy and gun drop the more then 30, this code store the data insade of the close_enemy array.

last line do the work, but it look every intanced enemies, as you guys can also see.

so i thought, i should add all the data to an array, and get the smallest one and use with look_at. but dont know how.

i will use look_at so that gun can look at the closest one.

:bust_in_silhouette: Reply From: morningkingdom

Solve it,

var shoot_distance:float = 70
var close_enemy


func _physics_process(delta):


var all_enemy = get_tree().get_nodes_in_group("enemy")
for enemy in all_enemy:
	var gun2enemy_distance = translation.distance_to(enemy.translation)
	if gun2enemy_distance < shoot_distance:

		shoot_distance = gun2enemy_distance  ## ---> ## with this i storaged the current close enemy to shoot_distance ###	this is need the be reset ever time, shoot distance must be allways 70, so that guns can search enemys that close the guns 70 value. because of that i reset it every 1 second to 70 again.
	  
        close_enemy = enemy  ## --->## after get the current close_enemy

		oto_zone_reset() ##---> call the function that reset the search area again

		look_at(close_enemy.translation,Vector3.UP) ## ---> look at the close_enemy
		print (shoot_distance)




func oto_zone_reset():
	yield(get_tree().create_timer(1),"timeout")
	shoot_distance = 70
	print ("shoot distance got reset")

output:

well, i think its still crude, so if you guys and gals have any option, or diffrent solutions, please write down, cause i need it. thank you. :slight_smile: