extends Node3D
## Tower Defense — Lecture 27 (Final)
##
## Projectile that flies toward target enemy and deals
## damage on contact. Self-destructs after hitting or
## if target is destroyed.

# ============================================================
# CONSTANTS
# ============================================================

const SPEED := 15.0
const MAX_LIFETIME := 5.0

# ============================================================
# STATE
# ============================================================

var target: Node3D = null
var damage: int = 10
var lifetime: float = 0.0

@onready var mesh_instance: MeshInstance3D = $MeshInstance3D

# ============================================================
# LIFECYCLE
# ============================================================

func _ready() -> void:
	# Set projectile color
	var material := StandardMaterial3D.new()
	material.albedo_color = Color.ORANGE
	material.emission_enabled = true
	material.emission = Color.ORANGE
	mesh_instance.set_surface_override_material(0, material)


func _process(delta: float) -> void:
	lifetime += delta
	
	# Destroy if too old
	if lifetime > MAX_LIFETIME:
		queue_free()
		return
	
	# Check if target is still valid
	if not target or not is_instance_valid(target):
		queue_free()
		return
	
	# Move toward target
	var direction := global_position.direction_to(target.global_position)
	global_position += direction * SPEED * delta
	
	# Look at target
	look_at(target.global_position, Vector3.UP)
	
	# Check if close enough to hit
	var distance := global_position.distance_to(target.global_position)
	if distance < 0.5:
		_hit_target()


# ============================================================
# COLLISION
# ============================================================

func _hit_target() -> void:
	if target and target.has_method("take_damage"):
		target.take_damage(damage)
	queue_free()
