extends Node2D

const SPEED = 30

var direction = 1
var is_dying = false

@onready var ray_cast_right: RayCast2D = $RayCastRight
@onready var ray_cast_left: RayCast2D = $RayCastLeft
@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var killzone_enemy: Area2D = $Killzone_enemy
@onready var collision_kill_player: CollisionShape2D = $KillzonePlayer/CollisionShape2D
@onready var collision_kill_enemy: CollisionShape2D = $Killzone_enemy/CollisionShape2D

func _ready() -> void:
	killzone_enemy.body_entered.connect(_on_killzone_body_entered)

func _process(delta: float) -> void:
	if ray_cast_right.is_colliding():
		direction = -1
		animated_sprite_2d.flip_h = true
	elif ray_cast_left.is_colliding():
		direction = 1
		animated_sprite_2d.flip_h = false
	
	position.x += direction * SPEED * delta
	

func _on_killzone_body_entered(body: Node) -> void:
	if body.is_in_group("player") and not is_dying:
		is_dying = true
		collision_kill_player.set_deferred("disabled",true)
		animation_player.play("death")
		body.velocity.y = -300
		direction = 0
		collision_kill_enemy.set_deferred("disabled", true)
		await animation_player.animation_finished
		queue_free()
