| Attention | Topic was automatically imported from the old Question2Answer platform. | |
| Asked By | alhoot |
Hi, I am working on a 2D game
I encountered this problem and I do not know how to solve it … Please help me, as my experience in the godot engine is not great
this is the code of my enemy >>
extends Node
const MAX_RANGE = 150
@export var sword_ability : PackedScene
# Called when the node enters the scene tree for the first time.
func _ready():
$Timer.timeout.connect(on_timer_timeout)
func on_timer_timeout():
var player = get_tree().get_first_node_in_group("player") as Node2D
if player ==null:
return
var enemies = get_tree().get_first_node_in_group("enemy")
enemies = enemies.filter(func(enemy:Node2D):
return enemy.global_position.distance_squared_to(player.global_position) < pow(MAX_RANGE,2))
if enemies.size() == 0:
return
enemies.sort_custom(func(a: Node2D, b:Node2D):
var a_distance = a.global_position.distance_squared_to(player.global_position)
var b_distance = b.global_position.distance_squared_to(player.global_position)
return a_distance < b_distance
)
var sword_instance = sword_ability.instantiate() as Node2D
player.get_parent().add_child(sword_instance)
sword_instance.global_position = enemies[0].global_position
There is no text error in the code, but I don’t know where the problem is!..HELP ME
Instead of var enemies = get_tree().get_first_node_in_group("enemy") shouldn’t it be var enemies = get_tree().get_nodes_in_group("enemy")? Since you want to filter an array of the nodes contained in the group "enemy"…
Joel Gomes da Silva | 2023-07-05 16:41
@alhoot Edited to format the code. Use the Code Sample button.
Zylann | 2023-07-05 17:04
Its wooorking
thank you
alhoot | 2023-07-05 18:19