66 lines
1.6 KiB
GDScript
66 lines
1.6 KiB
GDScript
extends CharacterBody2D
|
|
|
|
@export var speed: float = 100.0
|
|
@export var max_health: float = 100.0
|
|
var current_health: float
|
|
|
|
var player: Node2D
|
|
@onready var health_bar = $HealthBar
|
|
@onready var turret = $Turret
|
|
|
|
@export var bullet_scene: PackedScene = preload("res://scenes/bullet.tscn")
|
|
@export var fire_rate: float = 2.0
|
|
var can_shoot: bool = true
|
|
|
|
func _ready():
|
|
add_to_group("enemy")
|
|
current_health = max_health
|
|
if health_bar:
|
|
health_bar.max_value = max_health
|
|
health_bar.value = current_health
|
|
health_bar.hide() # Hide initially, show on damage
|
|
|
|
# Find the player in the scene tree
|
|
player = get_tree().get_first_node_in_group("player")
|
|
if not player:
|
|
# Fallback: try to find by name if group not set
|
|
player = get_parent().get_node_or_null("player")
|
|
|
|
func _physics_process(_delta):
|
|
if player:
|
|
var direction = (player.global_position - global_position).normalized()
|
|
velocity = direction * speed
|
|
rotation = direction.angle()
|
|
move_and_slide()
|
|
|
|
# Aim turret at player
|
|
if turret:
|
|
turret.look_at(player.global_position)
|
|
|
|
# Shoot if close enough
|
|
if global_position.distance_to(player.global_position) < 400.0 and can_shoot:
|
|
shoot()
|
|
|
|
func shoot():
|
|
var bullet = bullet_scene.instantiate()
|
|
bullet.shooter_group = "enemy"
|
|
get_tree().root.add_child(bullet)
|
|
bullet.global_position = turret.global_position
|
|
bullet.global_rotation = turret.global_rotation
|
|
|
|
can_shoot = false
|
|
await get_tree().create_timer(fire_rate).timeout
|
|
can_shoot = true
|
|
|
|
func take_damage(amount: float):
|
|
current_health -= amount
|
|
if health_bar:
|
|
health_bar.show()
|
|
health_bar.value = current_health
|
|
|
|
if current_health <= 0:
|
|
die()
|
|
|
|
func die():
|
|
queue_free()
|