Killzone not working with moving enemy

Godot Version

4.7.1.stable.official

Question

Hello!

I’m doing my first game ever, an 2d platform.

I have a player (CharacterBody2D) and a killzone that it detects the player a timer is started and when it ends all the scene reload.

extends Area2D

@export var killzone: Area2D
@onready var timer: Timer = $Timer
@onready var audio_stream_player_2d: AudioStreamPlayer2D = $AudioStreamPlayer2D
var dead = false

func _on_timer_timeout() -> void:
	get_tree().reload_current_scene()


func _on_body_entered(body: Node2D) -> void:
	if dead == false and (body.name == "CharacterBody2D" or body.name == "player"):
		dead = true
		print("You died!")
		timer.timeout.connect(_on_timer_timeout)
		timer.start()

And the Player has this code from when he dies:

func _on_hitbox_area_entered(area: Area2D) -> void:
	print(area.name)
	if area.name == "Killzone" or area.name == "killzone":
		animated_sprite_2d.play("death")
		hitbox_collider.set_deferred("disabled", true)
		death_sfx.play()
		set_physics_process(false)

This code works perfectly with every enemy I have except one:

It has a Killzone that when activated the timer doesn’t start and my player is not killed.

I tried multiple things to make it work but nothing seem to do.

Here is the code of the enemy:

extends Node2D
@onready var ray_cast_2d: RayCast2D = $RayCast2D

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	ray_cast_2d.add_exception($"../CharacterBody2D")
	ray_cast_2d.add_exception($"../player")

func _process(delta: float) -> void:
	position.x -= 100 * delta
	if ray_cast_2d.is_colliding():
		queue_free()

I’ve not used Raycast2D’s before but by looking at the documentation and your code, you’re adding exceptions to ignore the player.

The raycast I used it for deleting the object when enters in contact with other objects like the tiles of the map and others enemies.

Check colision layers and masks.

I found the problem: when the enemy touch the player the killzone was activated but not the sufficient to reset the tree because the raycast2d made the enemy disappear.

This is the correct code to resolve this problem:

extends Node2D
@onready var ray_cast_2d: RayCast2D = $RayCast2D
@onready var killzone: Area2D = $Killzone
@onready var sprite_2d: Sprite2D = $Sprite2D

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	ray_cast_2d.add_exception($"../CharacterBody2D")
	ray_cast_2d.add_exception($"../player")

func _process(delta: float) -> void:
	position.x -= 100 * delta
	if killzone.dead == true:
		print(killzone.body_entered.get_connections())
		ray_cast_2d.set_deferred("enabled", false)
		sprite_2d.set_deferred("visible", false)
		
	if ray_cast_2d.is_colliding():
		queue_free()