Can't get more than 1 body colliding with hitbox

Godot Version

4.3

Question

About 2 weeks ago I started learning how to create 2d games on godot. Right now I am working at simple tower defense game and I have a problem with my code. In this game I have to check if enemy enters an attack zone and if somebody does I add them to a list of bodies which collides with it. But bcs of a reason I don’t know if a body collides with the attack zone, signal “on_body_entered” stops working
and i can’t get bodies which are collided until the first entered in attack zone body don’t exit this zone.

extends CharacterBody2D

const SPEED = 100
const DAMAGE = 10

@onready var anim = $AnimatedSprite2D
@onready var attackBox = $AttackArea/AttackBox

var angry = 0
var readyToChill
var attackedObject = 0
var canAttack = 1
var hp = 100

var attackableObjects = ["Castle", "playersSwordMan"]
var collidingObjects = []



func _process(delta: float) -> void:
	if len(collidingObjects) > 0:
		angry = 1
	else:
		angry = 0
	
	if not attackedObject and angry:
		attackedObject = collidingObjects[0]
	if attackedObject and angry and attackedObject != collidingObjects[0]:
		attackedObject = 0
	
	if not angry:
		attackedObject = 0
		anim.play("walk")
		position.x -= SPEED * delta
	else:
		anim.play("attack")
		if anim.frame == 4 and canAttack:
			canAttack = 0
			attackedObject.hp -= DAMAGE
			#print("hp - ",attackedObject.hp)
		elif anim.frame != 4:
			canAttack = 1
			
	if self.hp <= 0:
		queue_free()

func _on_attack_area_body_entered(body: Node2D) -> void:
	print(body.name, " collided")
	if body.name in attackableObjects:
		collidingObjects.append(body)
		print("array length after colliding - ",len(collidingObjects))
		

func _on_attack_area_body_exited(body: Node2D) -> void:
	if body.name in attackableObjects:
		collidingObjects.erase(body)
		print("array length after killing - ",len(collidingObjects))

It would be nice if somebody could help me with it.

Just to be clear, if you run the game as it is, nothing is being printed to the console?

This can be caused by many different things. Here’s a checklist that includes some of the more common reasons:

  • Make sure both nodes (tower and enemies) share the same collision layer
  • Make sure the enemy is actually a PhysicsBody and not an Area2D. If it is an Area2D then use the signals related to areas.
  • Make sure the signal you’re using is actually connected. I personally prefer connecting in script inside _ready(): attack_box.body_entered.connect(on_attack_box_body_entered)

I would also warn against using name to identify the nodes. Once you instantiate more than one object of the same node, the autogenerated names might not match what you have set already. Consider using groups: Groups

thanks for help bro! I stopped checking which body collided with area using it’s name and this worked

1 Like