87 lines
2.1 KiB
GDScript
87 lines
2.1 KiB
GDScript
extends CharacterBody2D
|
|
class_name Enemy
|
|
|
|
@onready var animplayer = $AnimationPlayer
|
|
@onready var animplayerGun = $AnimationPlayerGun
|
|
@onready var shoot_raycast = $ShootRaycast
|
|
@onready var shoot_sound = $EnemyShotSound
|
|
@onready var hurt_sound = $HurtSound
|
|
|
|
var player: Player = null
|
|
|
|
var hit_chance: float = 0.3
|
|
var speed: float = 100.0
|
|
var direction := Vector2.ZERO
|
|
var stop_distance := 200.0
|
|
var hit_points: int = 3
|
|
var justShot: bool = false
|
|
|
|
func _process(delta: float) -> void:
|
|
if player != null:
|
|
look_at(player.global_position)
|
|
|
|
func _physics_process(delta: float) -> void:
|
|
if player != null:
|
|
var enemy_to_player = (player.global_position - global_position)
|
|
await get_tree().create_timer(0.5).timeout
|
|
enemy_shoot()
|
|
if enemy_to_player.length() > stop_distance:
|
|
direction = enemy_to_player.normalized()
|
|
else:
|
|
direction = Vector2.ZERO
|
|
|
|
if direction != Vector2.ZERO:
|
|
velocity = speed * direction
|
|
else:
|
|
velocity.x = move_toward(velocity.x, 0, speed)
|
|
velocity.y = move_toward(velocity.y, 0, speed)
|
|
|
|
move_and_slide()
|
|
|
|
#func _on_hit_box_body_entered(body: Node2D) -> void:
|
|
#pass
|
|
|
|
|
|
func _on_player_detector_body_entered(body: Node2D) -> void:
|
|
if body is Player:
|
|
if player == null:
|
|
player = body
|
|
print (name + " found the player")
|
|
|
|
|
|
func _on_player_detector_body_exited(body: Node2D) -> void:
|
|
if body is Player:
|
|
if player != null:
|
|
player = null
|
|
print (name + " lost the player")
|
|
|
|
func take_damage(amount: int):
|
|
if amount > 0:
|
|
hit_points -= amount
|
|
hurt_sound.play()
|
|
animplayer.play("take_damage")
|
|
if hit_points <= 0:
|
|
print(name +" died")
|
|
queue_free()
|
|
|
|
func enemy_shoot():
|
|
if justShot != true:
|
|
shoot_sound.play()
|
|
animplayerGun.play("enemy_gun_shot_flare")
|
|
enemy_shot_check()
|
|
justShot = true
|
|
await get_tree().create_timer(1.0).timeout
|
|
justShot = false
|
|
|
|
func enemy_shot_check():
|
|
if shoot_raycast.is_colliding():
|
|
var collider = shoot_raycast.get_collider()
|
|
if collider is StaticBody2D:
|
|
print("Shot a box!")
|
|
elif collider is Player:
|
|
if randf() < hit_chance:
|
|
print("Hit the Player!")
|
|
player.take_damage(1)
|
|
else:
|
|
print("Shot missed the Player!")
|