fuzzyworld

godot-shooter / starfield-background / files / Enemy.gd

Branch starfield-background · default branch · all branches

Enemy.gd

1.8 KB · history · blame

1extends KinematicBody2D
2
3onready var ray_cast_2d: RayCast2D = $RayCast2D
4onready var scene_tree: SceneTree = get_tree()
5const utils = preload("res://Utils.gd")
6var Explosion = preload("res://Explosion.tscn")
7
8export var move_speed = 100
9export var health: int = randi() % 8 + 2
10export var max_health = 10
11
12var velocity = Vector2.ZERO
13
14var dead = false
15
16func _process(delta: float) -> void:
17 $Graphics/Alive/Container/HealthLabel.text = "%s / %s" % [health, max_health]
18 $Graphics/Alive/Container.global_rotation = 0
19
20func _physics_process(delta: float) -> void:
21 if dead:
22 return
23 var players = scene_tree.get_nodes_in_group("player")
24 var player: KinematicBody2D = players[0]
25 var dist_to_player = global_position.distance_to(player.global_position)
26
27 var dir_to_player = global_position.direction_to(player.global_position)
28 var angle_to_player = dir_to_player.angle() + PI / 2.0
29 var vel = dir_to_player * move_speed
30 global_rotation = angle_to_player
31 velocity = move_and_slide(vel)
32
33 var ray_length = ray_cast_2d.cast_to.length()
34 if ray_cast_2d.is_colliding() and ray_cast_2d.get_collider() == player and dist_to_player < (ray_length + 5):
35 player.hurt()
36 var push = to_global(ray_cast_2d.cast_to) - to_global(Vector2.ZERO)
37 player.position += (push * 2)
38 player.velocity = player.move_and_slide(player.velocity)
39
40func hurt():
41 if dead:
42 return
43 utils.log("zombie is hurt, health was ", health)
44 health -= 1
45 if health <= 0:
46 kill()
47
48func kill():
49 if dead:
50 return
51 utils.log("zombie is dead")
52 dead = true
53 $Graphics/Alive.hide()
54 var explosion = Explosion.instance()
55 explosion.connect("explosion_done", self, "_on_death_explosion_finished")
56 $Graphics.add_child(explosion)
57 $CollisionPolygon2D.disabled = true
58 z_index = -1
59
60func _on_death_explosion_finished():
61 utils.log("removing zombie after explosion finished")
62 queue_free()