-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathghost.gd
More file actions
55 lines (45 loc) · 1.54 KB
/
ghost.gd
File metadata and controls
55 lines (45 loc) · 1.54 KB
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
extends CharacterBody2D
@export var speed: float = 80.0
@export var ghost_color_name: String = "red" # red, blue, pink
@export var behavior: String = "chaser" # "chaser" or "random"
var directions = [Vector2.UP, Vector2.DOWN, Vector2.LEFT, Vector2.RIGHT]
var current_dir: Vector2 = Vector2.ZERO
var scared: bool = false
var pacman: Node = null
func _ready():
pacman = get_tree().current_scene.get_node("Pacman")
add_to_group("Ghosts")
pick_new_direction()
update_animation()
func _physics_process(delta):
# Decide movement direction
if behavior == "chaser" and pacman:
var dir_to_pacman = (pacman.global_position - global_position).normalized()
if abs(dir_to_pacman.x) > abs(dir_to_pacman.y):
current_dir = Vector2(sign(dir_to_pacman.x), 0)
else:
current_dir = Vector2(0, sign(dir_to_pacman.y))
elif behavior == "random" and randf() < 0.02:
pick_new_direction()
position += current_dir * speed * delta
# Update animation
update_animation()
func pick_new_direction():
current_dir = directions[randi() % directions.size()]
func update_animation():
var prefix = ""
if scared:
prefix = "red_"
else:
prefix = ghost_color_name + "_"
if current_dir == Vector2.DOWN:
$AnimatedSprite2D.animation = prefix + "down"
elif current_dir == Vector2.LEFT:
$AnimatedSprite2D.animation = prefix + "left"
elif current_dir == Vector2.RIGHT:
$AnimatedSprite2D.animation = prefix + "right"
$AnimatedSprite2D.play()
func _on_area_2d_body_entered(body: Node2D) -> void:
# Check if the ghost hit Pac-Man
if body.is_in_group("Pacman"):
body.lose_life()