Godot Version
4
Question
`The distance that the enemy makes is equal to the detection area radius
Here is the enemy script
extends CharacterBody2D
var current_state = IDLE
var speed = 60
var player_chase = false
var player = null
var direction = Vector2.RIGHT
var health = 80
var player_in_attack_zone = false
var roaming = true
var can_take_damage = true
var enemy_alive = true
enum {
IDLE,
NEW_DIRECTION,
MOVE
}
func _ready():
pass
func _process(delta):
if Global.game_started == true:
deal_with_damage()
uptade_health()
if enemy_alive == true:
if roaming :
match current_state:
IDLE:
pass
NEW_DIRECTION:
direction = choose([Vector2.RIGHT, Vector2.UP, Vector2.LEFT, Vector2.DOWN])
MOVE :
move(delta)
if player_chase :
position += (player.position - position) / speed
if Global.player_alive == false:
player_chase = false
$AnimatedSprite2D.play("walk")
if (player.position.x - position.x) < 0 :
$AnimatedSprite2D.flip_h = true
else :
$AnimatedSprite2D.flip_h = false
else :
$AnimatedSprite2D.play("idle")
func _on_detection_area_body_entered(body):
player = body
if Global.player_alive == true:
player_chase = true
else:
player_chase = false
func _on_detection_area_body_exited(body):
player = null
player_chase = false
func enemy():
pass
func _on_enemy_hitbox_body_entered(body):
if body.has_method(“player”):
player_in_attack_zone = true
func _on_enemy_hitbox_body_exited(body):
if body.has_method(“player”):
player_in_attack_zone = false
func deal_with_damage():
if player_in_attack_zone and Global.player_current_attack == true :
if can_take_damage == true and health != 0:
health -= 20
$damage_cooldown.start()
can_take_damage = false
print("slime health = ", health)
if health <= 0:
health = 0
enemy_alive = false
$AnimatedSprite2D.play(“death”)
await get_tree().create_timer(1).timeout
self.queue_free()
func uptade_health():
var healthbar = $healthbar
healthbar.value = health
if health >= 100:
healthbar.visible = false
else :
healthbar.visible = true
func _on_damage_cooldown_timeout():
can_take_damage = true
func choose(array):
array.shuffle()
return array.front()
func move(delta):
if !player_in_attack_zone:
position += direction * speed * delta
func _on_wait_time_timer_timeout():
$wait_time_timer.wait_time = choose([0.2, 0.5, 1, 1.5])
current_state = choose([IDLE, NEW_DIRECTION,MOVE])