summaryrefslogtreecommitdiff
path: root/Enemies/enemy.gd
blob: eed482d7c966556c03c34b96c5dc74d87a980282 (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
class_name Enemy
extends CharacterBody2D


@export var speed: float = 30.0

var direction = -1 :
	set(value):
		direction = value
		$AnimatedSprite2D.flip_h = direction > 0

@onready var disable_timer = Timer.new()


func _ready() -> void:
	disable_timer.wait_time = 3.0
	disable_timer.one_shot = true
	disable_timer.timeout.connect(_on_disable_timer_timeout)
	add_child(disable_timer)
	
	process_mode = PROCESS_MODE_DISABLED


func _physics_process(delta: float) -> void:
	$AnimatedSprite2D.play()
	
	if not is_on_floor():
		velocity += get_gravity() * delta
	
	velocity.x = direction * speed
	
	move_and_slide()
	if get_last_slide_collision():
		if $RayLeft.is_colliding():
			direction = 1
		elif $RayRight.is_colliding():
			direction = -1


func on_hit(projectile_position: Vector2):
	var impact_direction = global_position - projectile_position
	var impact_direction_x = sign(impact_direction.x)
	
	var effect_star_scene := preload("res://effect_star.tscn")
	
	var directions = []
	if randi() % 10 > 5:
		directions = [Vector2(1, 1) * 8, Vector2(1, -1) * 8, Vector2(-1, -1) * 8, Vector2(-1, 1) * 8]
	else:
		directions = [
			Vector2(impact_direction_x, 1) * 16,
			Vector2(impact_direction_x, -1) * 16,
			Vector2(impact_direction_x, 0.25) * 16,
			Vector2(impact_direction_x, -0.25) * 16,
		]
	
	for effect_direction in directions:
		var effect_star := effect_star_scene.instantiate()
		effect_star.global_position = global_position
		get_tree().current_scene.add_child(effect_star)
		var tween := get_tree().create_tween().set_ease(Tween.EASE_OUT)
		tween.tween_property(
			effect_star,
			"global_position",
			global_position + effect_direction,
			0.1
		)
		tween.tween_callback(func():
			effect_star.queue_free()
		).set_delay(0.2)
	
	queue_free()


func _on_visible_on_screen_notifier_2d_screen_entered() -> void:
	disable_timer.stop()
	process_mode = PROCESS_MODE_INHERIT

func _on_visible_on_screen_notifier_2d_screen_exited() -> void:
	disable_timer.start()

func _on_disable_timer_timeout():
	process_mode = PROCESS_MODE_DISABLED