extends CharacterBody2D

const SPEED = 300
const JUMP_VELOCITY = -400.0
const ANGULAR_ACCELERATION = 7.5;

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var direction: int
var World: Node2D
var ap: AnimationPlayer
var asp: AudioStreamPlayer
var jumping: bool = false
var lives: int = 3

var jump_sound = preload("res://audio/jump.wav")
var land_sound = preload("res://audio/land.wav")
var fall_sound = preload("res://audio/fall.wav")
var switch_direction_sound = preload("res://audio/switch_direction.wav")

func switch_direction():
	velocity.x *= -1
	direction *= -1
	asp.stream = switch_direction_sound
	asp.play()

func _ready():
	ap = $AnimationPlayer;
	asp = $AudioStreamPlayer;
	World = get_node("/root/World") ## why did get_world("World") didn't work?
	direction = World.direction ## maybe should be getting initial direction from level

func _physics_process(delta):
	
	if Input.is_action_just_pressed("debug"):
		switch_direction()
	#if direction != World.direction:
			#swap_direction()
		
	# Add the gravity.
	self.up_direction = -World.gravity_vector;
	$CollisionShape2D.skew = lerp( $CollisionShape2D.skew, (.001) * self.velocity.x * sin(World.gravity_vector.angle()) , delta * ANGULAR_ACCELERATION )
	self.rotation = lerp( self.rotation , -World.gravity_vector.angle() + (.5*PI) , delta * ANGULAR_ACCELERATION ) ;
	
	
	if not is_on_floor(): 
		velocity.y += gravity * (sin(World.gravity_vector.angle())) * delta
		velocity.x += gravity * (cos(World.gravity_vector.angle())) * delta
	else:
		# Handle jump.
			
		if jumping:
			jumping = false
			ap.play("land")
			asp.stream = land_sound
			asp.play()
			
			
		if Input.is_action_just_pressed("jump") and is_on_floor():
			#velocity.x = JUMP_VELOCITY * cos(jump_vector.angle())
			jumping = true
			ap.play("jump")
			asp.stream = jump_sound
			asp.play()
			
			velocity.y = JUMP_VELOCITY * sin(World.gravity_vector.angle()) 
					
		if direction != 0:
			velocity.x = direction * SPEED
		else:
			velocity.x = move_toward(velocity.x, 0, SPEED)
					
	move_and_slide()

func _on_fall():
	asp.stream = fall_sound
	asp.play()
