summaryrefslogtreecommitdiffstats
path: root/scripts/PlayerCharacter.gd
blob: 8e2b83a9a70c2b316ab4bc13302a408e54896fb5 (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
extends KinematicBody2D
class_name PlayerCharacter

export (int) var speed = 8
export (float) var walk_wobble_coeff = 5
onready var gui: GUI = get_tree().get_root().get_node("Game/CanvasLayer/GUI")
onready var game: Game = get_tree().get_root().get_node("Game")

signal initiate_dialogue(other)

var velocity = Vector2()
var look_dir = 1 # right = 1, left  = -1
var in_dialogue: bool = false
enum DialogueState {
	ACTIVE, # when dialogue in progress with a target
	ENDED, # when dialogue exhausted via GUI
	WALKED_OFF # when character moves out from dialogue target
}
var dialogue_state = DialogueState.WALKED_OFF

func _ready():
	yield(get_tree(), "idle_frame")
	var err = game.connect("dialogue_end", self, "_on_Game_dialogue_end")
	if err:
		push_error(err)

func update_input_and_movement():
	velocity = Vector2()
	if Input.is_action_pressed('ui_right'):
		velocity.x += 1
	if Input.is_action_pressed('ui_left'):
		velocity.x -= 1
	if Input.is_action_pressed('ui_down'):
		velocity.y += 1
	if Input.is_action_pressed('ui_up'):
		velocity.y -= 1

	velocity = velocity.normalized() * speed
	velocity = move_and_slide(velocity)

func _process(_delta):
	# Update walking wobble
	var is_moving = velocity.length_squared() > .0 and dialogue_state != DialogueState.ACTIVE
	if is_moving:
		var time = OS.get_system_time_msecs() / 1000.0
		var rot = 0.2 * sin(walk_wobble_coeff * time)
		$Sprite.set_rotation(rot)
	else:
		$Sprite.set_rotation(0)
		
	# Look at walking direction
	if velocity[0] > .0:
		look_dir = 1
	elif velocity[0] < .0:
		look_dir = -1

	$Sprite.set_scale(Vector2(look_dir, 1))

func _physics_process(_delta):
	if dialogue_state != DialogueState.ACTIVE:
		update_input_and_movement()

	var slide_count = get_slide_count()
	if slide_count == 0 and dialogue_state == DialogueState.ENDED:
		dialogue_state = DialogueState.WALKED_OFF

	# If the player is colliding with a Dialogue group node and does not have an
	# active dialogue, run dialogue with the node
	for idx in slide_count:
		var coll = get_slide_collision(idx)
		if coll.collider.is_in_group("Dialogue") and dialogue_state == DialogueState.WALKED_OFF:
			dialogue_state = DialogueState.ACTIVE
			emit_signal("initiate_dialogue", coll.collider)
			break
			
func _on_Game_dialogue_end():
	dialogue_state = DialogueState.ENDED