extends KinematicBody2D

const SPEED: int = 400 # (pixels/sec).
const GRAVITY: int = 20
const JUMP_POWER: int = -600
const FLOOR: Vector2 = Vector2(0, -1)
var screen_size: Vector2
var velocity: Vector2 = Vector2.ZERO
var on_ground: bool = false
var count: int = 0
var on_moth1: int = 0
var on_moth2: int = 0
var on_butterfly1: int = 0

signal on_finish

func _ready():
	screen_size = get_viewport_rect().size #find the size of the game window

func _physics_process(delta):
	#Set movement direction
	if Input.is_action_pressed("move_right"):
		velocity.x = SPEED
	elif Input.is_action_pressed("move_left"):
		velocity.x = -SPEED
	else:
		velocity.x = 0

	if Input.is_action_pressed("move_up"):
		if on_ground == true:
			velocity.y = JUMP_POWER
			on_ground = false

	velocity.y += GRAVITY
	
	if is_on_floor():
		on_ground = true
	else:
		on_ground = false

	velocity = move_and_slide(velocity, FLOOR)

	#change which animation the AnimatedSprite is playing based on its direction
	if velocity.x != 0:
		if velocity.x < 0:
			$AnimatedSprite.animation = "walk"
			$AnimatedSprite.flip_h = true
		elif velocity.x > 0:
			$AnimatedSprite.animation = "walk"
			$AnimatedSprite.flip_h = false
		elif on_ground == true:
			$AnimatedSprite.animation = "still"
	elif velocity.y != 0:
		if velocity.y < 0:
			$AnimatedSprite.animation = "jump"
	else:
		if on_ground == false:
			$AnimatedSprite.animation = "jump"
		else:
			$AnimatedSprite.animation = "still"

func _on_FinishLine_body_entered(body):
	count += 1
	if count > 1:
		emit_signal("on_finish")

func _on_Moth1_body_entered(body):
	if on_moth1 < 1:
		$Moth1.play()
		on_moth1 += 1
		yield(get_tree().create_timer(5), "timeout")
		on_moth1 = 0

func _on_Moth2_body_entered(body):
	if on_moth2 < 1:
		$Moth2.play()
		on_moth2 += 1
		yield(get_tree().create_timer(5), "timeout")
		on_moth2 = 0

func _on_Butterfly1_body_entered(body):
	if on_butterfly1 < 1:
		$Butterfly1.play()
		on_butterfly1 += 1
		yield(get_tree().create_timer(5), "timeout")
		on_butterfly1 = 0
