Help, my code removes Health from every enemy

I am creating a 2D base defense game where waves of enemies have to be fought of.
im am currently trying to create the Health system. My code is designed to find the closest target and just remove some health when my raycast_2d is colliding.

This is my current code:

extends CharacterBody2D

@onready var animated_sprite_2d = $AnimatedSprite2D
@onready var ray_cast_2d = $RayCast2D

const SPEED = 50
var MOVEMENT = SPEED
var HEALTH = 100
var ATTACK = 25
var MOTION = Vector2.ZERO

func _physics_process(delta):
	var curr_tar : Node2D
	var targets : Array = get_tree().get_nodes_in_group("enemy_troops")
	if targets:
		var shortest_distance : float = global_position.distance_to(targets[0].global_position)
		curr_tar = targets[0]
		for i in targets:
			var curr_dist : float = global_position.distance_to(i.global_position)
			if curr_dist < shortest_distance:
				curr_tar = i
				shortest_distance = curr_dist
		position = position.move_toward(curr_tar.global_position, delta * MOVEMENT)
	print(curr_tar)
	if ray_cast_2d.is_colliding():
		MOVEMENT = 0
		animated_sprite_2d.play("attack")
		curr_tar.HEALTH -= 100
	else:
		MOVEMENT = SPEED
		animated_sprite_2d.play("run")

	#DEATH
	if HEALTH <= 0:
		queue_free()

The Problem is that as soon as my first entity collides with a enemy, all enemy troops will have Health removed, anyone has an Idea how to fix that?

pls help
Birrd

My assumption is that ray_cast_2d is always colliding so removes all enemies as the code always finds one from the enemy_troops group.

1 Like
curr_tar = targets[0]
		for i in targets:
			var curr_dist : float = global_position.distance_to(i.global_position)
			if curr_dist < shortest_distance:
				curr_tar = i
				shortest_distance = curr_dist

I’ll bet this chunk of code is where your error is. It seems the problem is that you set curr_tar = i in your for loop, effectively setting your current target to every enemy every frame.

1 Like