summaryrefslogtreecommitdiff
path: root/Scenes/Entities/Enemies/Components/Health.gd
blob: 00bf9e016a604edd423e1892dce877bd303028ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class_name ComponentHealth
extends Node


signal hit
signal died

@export_node_path("CharacterBody2D") var entityPath: NodePath
@onready var entity: CharacterBody2D = get_node(entityPath)

@export_node_path("AnimatedSprite2D") var spritePath: NodePath
@onready var sprite: AnimatedSprite2D = get_node(spritePath)

@export_node_path("ComponentMovement") var component_movement_path: NodePath
var component_movement: ComponentMovement

@export var health: int

@export var drops_items: bool = true
@export_range(1, 100) var drop_chance: int = 30
var drop_items = [
	preload("res://Scenes/Entities/Objects/Coin.tscn"),
]

@export var invincibility_timeout: float = 1.0
var is_invincible = false


func _ready():
	if component_movement_path:
		component_movement = get_node(component_movement_path)


func take_damage():
	if is_invincible:
		return
	
	emit_signal("hit")
	
	health -= 1
	
	is_invincible = true
	if component_movement: # stop all movement
		component_movement.pause()
	
	sprite.play("death")
	await sprite.animation_finished
	
	if health <= 0:
		death()
	else:
		if component_movement: # resume all movement
			component_movement.unpause()
		
		#var flicker_speed = 0.2
		#var tween = create_tween().set_loops(invincibility_timeout / (flicker_speed*2))
		#tween.tween_property(sprite, "modulate", Color(1, 1, 1, 0.5), flicker_speed)
		#tween.tween_property(sprite, "modulate", Color(1, 1, 1, 1), flicker_speed)
		#
		#await get_tree().create_timer(invincibility_timeout).timeout
		is_invincible = false


func death():
	emit_signal("died")
	
	assert(sprite.sprite_frames.has_animation("death_post"))
	sprite.play("death_post")
	
	var tween: Tween = get_tree().create_tween()
	tween.tween_property(
		entity,
		"scale",
		Vector2(0, 0),
		1 / sprite.sprite_frames.get_animation_speed("death_post")
	)
	tween.tween_callback(func():
		if drops_items and randi_range(1, 100) <= drop_chance:
			call_deferred("drop_item")
		
		entity.queue_free()
	)


func drop_item():
	var item = drop_items.pick_random().instantiate()
	item.position = entity.position
	get_tree().current_scene.add_child(item)