extends CharacterBody2D


const SPEED = 400.0
const JUMP_VELOCITY = -800.0
@onready var sprite_2d = $Sprite2D
@onready var direction

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")


func _physics_process(delta):
	#Animations
	if (velocity.x > 1 || velocity.x < -1):
		sprite_2d.animation = "running"
		if $"../player_run".playing == false:
			$"../player_run".play()
	else:
		sprite_2d.animation = "idle"
		if $"../player_run".playing == true:
			$"../player_run".stop()
	
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity * delta
		sprite_2d.animation = "jump"
		if $"../player_run".playing == true:
			$"../player_run".stop()

	# Handle jump.
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		$"../player_jump".play()

	if Input.is_key_pressed(KEY_RIGHT) or Input.is_key_pressed(KEY_D):
		direction = 1
	elif Input.is_key_pressed(KEY_LEFT) or Input.is_key_pressed(KEY_A):
		direction = -1
	else:
		direction = 0
	if direction:
		velocity.x = direction * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, 20)
	
	move_and_slide()
	var isLeft = velocity.x < 0
	sprite_2d.flip_h = isLeft
	
	var playerPos = $".".position.x
	var tSpeed = 0.5
	var sOffset = -100.0
	var fOffset = -200.0
	if playerPos > 250:
		$"../Camera2D".offset.x = lerp($"../Camera2D".offset.x,fOffset,tSpeed*delta)
	else:
		$"../Camera2D".offset.x = lerp($"../Camera2D".offset.x,sOffset,tSpeed*delta)
