fuzzyworld

godot-shooter / meteor / files / Enemy.gd

Branch meteor · default branch · all branches

Enemy.gd

2.4 KB · history · blame

1extends KinematicBody2D
2class_name Enemy
3
4onready var ray_cast_2d: RayCast2D = $RayCast2D
5onready var damage_points = $DamagePoints
6const Utils = preload("res://Utils.gd")
7const Explosion = preload("res://Explosion.tscn")
8const Smoke = preload("res://Smoke.tscn")
9
10export var move_speed = 40
11export var health = -1
12export var max_health = 10
13export var is_targeted = false
14export var is_invincible = false
15signal enemy_killed
16
17var velocity = Vector2.ZERO
18var dead = false
19
20func _ready() -> void:
21 if health < 0 or health > max_health:
22 health = max_health
23 else:
24 var hurt_points = max_health - health
25 health = max_health
26 for i in hurt_points:
27 hurt()
28
29func _process(_delta: float) -> void:
30 $Graphics/Alive/Container/HealthLabel.text = "%s / %s" % [health, max_health]
31 $Graphics/Alive/Container.global_rotation = 0
32 $Graphics/Alive/Target.visible = is_targeted
33
34func _physics_process(_delta: float) -> void:
35 if dead:
36 return
37 var players = get_tree().get_nodes_in_group("player")
38 var player: Player = players[0]
39 if player.dead:
40 return
41 var dist_to_player = global_position.distance_to(player.global_position)
42 var dir_to_player = global_position.direction_to(player.global_position)
43 var angle_to_player = dir_to_player.angle() + PI / 2.0
44 var vel = dir_to_player * move_speed
45 global_rotation = angle_to_player
46 velocity = move_and_slide(vel)
47
48 var ray_length = ray_cast_2d.cast_to.length()
49 if ray_cast_2d.is_colliding():
50 if ray_cast_2d.get_collider() == player and dist_to_player < (ray_length + 5):
51 player.hurt(2)
52 var explosion = Explosion.instance()
53 explosion.transform = transform
54 get_parent().add_child(explosion)
55 kill()
56
57func hurt():
58 if dead || is_invincible:
59 return
60 health -= 1
61 var smoke = Smoke.instance()
62 var smoke_pos = get_damage_point_on_body()
63 smoke.position = smoke_pos
64 add_child(smoke)
65 if health <= 0:
66 kill()
67
68func kill():
69 if dead || is_invincible:
70 return
71 dead = true
72 $Graphics/Alive.hide()
73 $CollisionPolygon2D.queue_free()
74 var explosion = Explosion.instance()
75 explosion.connect("explosion_done", self, "_on_death_explosion_finished")
76 $Graphics.add_child(explosion)
77 z_index = -1
78 emit_signal("enemy_killed")
79
80func _on_death_explosion_finished():
81 $AnimationPlayer.play("fade_out")
82
83func get_damage_point_on_body() -> Vector2:
84 var child_count = damage_points.get_child_count()
85 var random_index = randi() % child_count
86 var random_child: Position2D = damage_points.get_child(random_index)
87 return random_child.position