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 gravity_vector: Vector2
var direction: int
var World: Node2D
var ap: AnimationPlayer
var asp: AudioStreamPlayer
var cam: Camera2D

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
	set_direction( direction * -1 )
	asp.stream = switch_direction_sound
	asp.play()

func _ready():
	ap = $AnimationPlayer;
	asp = $AudioStreamPlayer;
	
	
## Setters
func set_direction( d: int ):
	direction = d
	
func set_gravity_vector( gv: Vector2 ):
	gravity_vector = gv

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 = -gravity_vector;
	$CollisionShape2D.skew = lerp( $CollisionShape2D.skew, (.001) * self.velocity.x * sin(gravity_vector.angle()) , delta * ANGULAR_ACCELERATION )
	self.rotation = lerp( self.rotation , -gravity_vector.angle() + (.5*PI) , delta * ANGULAR_ACCELERATION ) ;
	
	
	if not is_on_floor(): 
		velocity.y += gravity * (sin(gravity_vector.angle())) * delta
		velocity.x += gravity * (cos(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(gravity_vector.angle()) 
					
		if direction != 0:
			velocity.x = direction * SPEED
		else:
			velocity.x = move_toward(velocity.x, 0, SPEED)
					
	move_and_slide()

#func _on_activate_camera():
	#print("is this being used?")
	#cam.make_current()
	
func fall():
	asp.stream = fall_sound
	asp.play()
