class_name Enemy extends CharacterBody2D const ball_scene = preload("res://scenes/ball.tscn") const ball_name = "Ball" const y_spawn_offset = -8 signal hit_ball var speed = 80 var next_destination var collide_with_ball = false var hit_ball_animation_finished = false var ball_aims_to_bottom = false @onready var tile_map: TileMap = get_parent() @onready var animation_player = $AnimationPlayer @onready var sprite = $Sprite2D func _ready(): var spawn_cell = tile_map.get_top_spawn_cell() position = tile_map.map_to_local(spawn_cell) + Vector2(0, y_spawn_offset) animation_player.animation_finished.connect(_on_hit_ball_animation_finished) func move_to(destination): var delta = get_physics_process_delta_time() position = position.move_toward(destination, delta * speed) func throw_ball(): var ball = ball_scene.instantiate() ball.name = ball_name ball.position = position ball.notify_enemy.connect(_on_notify_enemy) tile_map.add_child(ball) hit_ball.emit() func return_ball(): hit_ball.emit() func flip_sprite(destination): sprite.flip_h = position.x > destination.x func play_hit_ball_animation(): hit_ball_animation_finished = false animation_player.speed_scale = 0.8 animation_player.play("hit_ball") animation_player.speed_scale = 1 func play_idle_animation(): animation_player.play("idle") func play_walk_animation(): animation_player.play("walk") func _on_hit_ball_animation_finished(_anim_name): hit_ball_animation_finished = true func _on_notify_enemy(ball_target: Vector2i): if tile_map.is_in_bottom_area(ball_target): ball_aims_to_bottom = true else: ball_aims_to_bottom = false # TODO: add to ball_target an offset depending from where the enemy come from next_destination = tile_map.map_to_local(ball_target) func _on_area_2d_body_entered(_body): collide_with_ball = true func _on_area_2d_body_exited(_body): collide_with_ball = false func ball_in_game() -> bool: return tile_map.has_node(ball_name) # Debug functions func reset_tile(destination): destination.y -= y_spawn_offset var cell = tile_map.local_to_map(destination) tile_map.set_cell(0, cell, 0, Vector2i(0, 0), 0)